When working with Python, we often come across situations where we need to store data in key-value pairs. This is where the dictionary data type comes in handy. In this article, we will explore how to declare a dictionary data type in Python and how to work with it.
Declaring a Dictionary
To declare a dictionary in Python, we use curly braces ({}) and separate each key-value pair with a colon (:). The key is always unique and the value can be of any data type.
Here’s an example:
my_dict = {'name': 'John', 'age': 25, 'city': 'New York'}
In the above example, we have declared a dictionary called my_dict. It contains three key-value pairs: ‘name’ with the value ‘John’, ‘age’ with the value 25, and ‘city’ with the value ‘New York’.
Accessing Dictionary Values
To access values in a dictionary, we can use square brackets ([]). We provide the key inside the brackets to retrieve its corresponding value.
print(my_dict['name']) # Output: John print(my_dict['age']) # Output: 25 print(my_dict['city']) # Output: New York
In the above example, we are accessing values from my_dict. We provide the keys (‘name’, ‘age’, and ‘city’) inside square brackets to retrieve their respective values (‘John’, 25, and ‘New York’).
Modifying Dictionary Values
To modify the value of a specific key in a dictionary, we can simply assign a new value to that key.
my_dict['age'] = 30 print(my_dict) # Output: {'name': 'John', 'age': 30, 'city': 'New York'}
In the above example, we are modifying the value of the ‘age’ key in my_dict. After assigning a new value (30) to the ‘age’ key, we print the updated dictionary.
Dictionary Methods
Python provides various built-in methods to work with dictionaries. Let’s explore some commonly used ones:
keys()
The keys() method returns a list of all the keys present in a dictionary.
print(my_dict.keys()) # Output: ['name', 'age', 'city']
values()
The values() method returns a list of all the values present in a dictionary.values()) # Output: [‘John’, 30, ‘New York’]
items()
The items() method returns a list of tuples containing all the key-value pairs present in a dictionary.items()) # Output: [(‘name’, ‘John’), (‘age’, 30), (‘city’, ‘New York’)]
In Conclusion
Dictionaries are a powerful data type in Python that allow us to store and access data in key-value pairs. In this article, we learned how to declare a dictionary, access its values, modify them, and use some of the built-in methods available for dictionaries. With this knowledge, you can now effectively work with dictionary data types in your Python programs.