Python Dictionaries are an important data structure in Python that allows you to store data in a key-value pair. It is similar to a real-world dictionary where we have a word and its meaning. In Python, we have a key and its corresponding value. Dictionaries are mutable, and you can add, remove, and modify the elements in the dictionary. In this blog, we will learn about Python Dictionaries and explore some examples.
Creating a Python Dictionary:
You can create a dictionary using curly braces, and each key-value pair is separated by a comma. Here’s an example:
person = {'name': 'John', 'age': 25, 'address': 'New York'}
In the above example, ‘name’, ‘age’, and ‘address’ are the keys, and ‘John’, 25, and ‘New York’ are their corresponding values. You can access the values in the dictionary using the key:
print(person['name']) # Output: John
If you try to access a key that is not in the dictionary, you will get a KeyError. Therefore, it’s always better to check if the key exists in the dictionary or not before accessing it:
if 'name' in person: print(person['name']) # Output: John
Adding and Modifying Elements in a Dictionary:
You can add or modify elements in a dictionary using the key:
person = {'name': 'John', 'age': 25, 'address': 'New York'} person['age'] = 30 # modifying the age person['phone'] = '1234567890' # adding a new key-value pair print(person) # Output: {'name': 'John', 'age': 30, 'address': 'New York', 'phone': '1234567890'}
Removing Elements from a Dictionary:
You can remove an element from the dictionary using the del
keyword:
person = {'name': 'John', 'age': 25, 'address': 'New York'} del person['address'] # deleting the 'address' key print(person) # Output: {'name': 'John', 'age': 25}
Iterating over a Dictionary:
You can iterate over a dictionary using a for loop:
person = {'name': 'John', 'age': 25, 'address': 'New York'} for key in person: print(key, ':', person[key])
The output of the above code will be:
name : John age : 25 address : New York
Another way of iterating over a dictionary is to use the items()
method, which returns a list of tuples containing the key-value pairs:
person = {'name': 'John', 'age': 25, 'address': 'New York'} for key, value in person.items(): print(key, ':', value)
The output of the above code will be the same as the previous example.
Conclusion:
Python dictionaries are a powerful data structures that can help you store and manipulate data efficiently. In this blog, we have learned how to create, access, add, modify, and remove elements from a dictionary. We have also explored how to iterate over a dictionary. I hope this blog has given you a good understanding of Python dictionaries.