In the world of programming, a data dictionary, also known as a hash map or associative array, is a very useful structure for storing data.
In Python specifically, the dictionary data type is essential due to its flexibility and efficient data access. This tutorial will guide you through creating and manipulating data dictionaries in Python.
What is a Python dictionary?
A Python dictionary is an unordered collection of data values. Unlike other data types that hold only a single value as an element, a dictionary holds key:value pairs.
The keys in a dictionary must be immutable (like numbers or strings) and unique. However, the dictionary values can be of any type and can be duplicated.
Creating a Dictionary
To create a dictionary in Python, you use curly brackets {} and separate the keys and values with a colon. If you want to add more items, you can use a comma as a separator.
1 2 |
# create a dictionary details = {'name':'John', 'age':25, 'country':'USA'} |
You can also create a dictionary using the built-in dict() function.
1 2 |
# create a dictionary using dict() function details = dict(name='John', age=25, country='USA') |
Accessing Items
To access dictionary elements, you can use the familiar square brackets along with the key to obtain its value. You can also use the get() method to access the value.
1 2 3 |
# access elements from the dictionary print(details['name']) print(details.get('age')) |
Updating a Dictionary
Updating a dictionary means adding a new item or changing the value of an existing item. If the key already exists, then the existing value gets updated. In case the key is not present, a new key:value pair is added to the dictionary.
1 2 3 |
# update a dictionary details['age'] = 26 # update existing value details['profession'] = 'Doctor' # add new key:value pair |
Before the conclusion, let’s quickly review the full code content.
Full Code
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# create a dictionary details = {'name':'John', 'age':25, 'country':'USA'} # create a dictionary using dict() function details = dict(name='John', age=25, country='USA') # access elements from the dictionary print(details['name']) print(details.get('age')) # update a dictionary details['age'] = 26 # update existing value details['profession'] = 'Doctor' # add new key:value pair |
John 25
Conclusion
Learning how to create and manipulate a Python dictionary is essential if you’re looking to become proficient in the Python programming language.
They offer flexibility and efficient data access to make your programming tasks easier. Remember to use curly brackets or the dict() function to create dictionaries, access elements with keys, and update your dictionaries by adding or modifying key:value pairs as needed.