Understanding Python Nested Dictionaries
In Python, a dictionary is a collection of key-value pairs. It allows you to store and retrieve data using a unique key as an identifier. A nested dictionary, as the name suggests, is a dictionary within another dictionary. This means that the value associated with a key in a dictionary can be another dictionary.
Creating a Nested Dictionary
To create a nested dictionary in Python, you can simply assign a dictionary as the value to a key in another dictionary. Here’s an example:
“`python
student = {
“name”: “John”,
“age”: 20,
“grades”: {
“math”: 95,
“science”: 90,
“history”: 85
}
}
“`
In the above example, the “grades” key in the “student” dictionary has a value that is another dictionary. This allows you to store additional information related to the student’s grades.
Accessing Values in a Nested Dictionary
To access the values in a nested dictionary, you can use multiple square brackets to specify the keys at each level. Here’s how you can access the grade in math for the student:
“`python
math_grade = student[“grades”][“math”]
print(math_grade) # Output: 95
“`
In the above example, the first square brackets access the value associated with the key “grades” in the “student” dictionary, which is another dictionary. The second square brackets access the value associated with the key “math” in the nested dictionary.
Modifying Values in a Nested Dictionary
You can modify the values in a nested dictionary by using the same syntax as accessing the values. Here’s an example:
“`python
student[“grades”][“history”] = 90
print(student[“grades”][“history”]) # Output: 90
“`
In the above example, the value associated with the key “history” in the nested dictionary is modified to 90.
Iterating Over a Nested Dictionary
You can iterate over a nested dictionary using nested loops. Here’s an example:
“`python
student = {
“name”: “John”,
“age”: 20,
“grades”: {
“math”: 95,
“science”: 90,
“history”: 85
}
}
for key, value in student.items():
if isinstance(value, dict):
print(f”{key}:”)
for sub_key, sub_value in value.items():
print(f” {sub_key}: {sub_value}”)
else:
print(f”{key}: {value}”)
“`
In the above example, the outer loop iterates over the key-value pairs in the “student” dictionary. If the value is another dictionary, the inner loop iterates over the key-value pairs in the nested dictionary. This allows you to print all the information stored in the nested dictionary.
Conclusion
Nested dictionaries in Python provide a convenient way to organize and access complex data structures. They allow you to store and retrieve data in a hierarchical manner, making it easier to represent real-world relationships. By understanding how to create, access, modify, and iterate over nested dictionaries, you can effectively work with complex data in your Python programs.