Nested Dictionaries
In this tutorial, we'll explore the concept of nested dictionaries in Python. Nested dictionaries are dictionaries that are stored within another dictionary.
Nested dictionaries are very useful for representing more complex data structures.
What are Nested Dictionaries?
-
A nested dictionary is a dictionary that can contain other dictionaries as its values.
-
In simple words, we can say it is a dictionary inside another dictionary.
Creating a Nested Dictionary
To create a nested dictionary, we can define a dictionary inside another dictionary. Here's an example:
Example:
student = {
'name': 'Rohan',
'info': {
'age': 19,
'course': 'B.Tech'
}
}
print(student)
Output:
{'name': 'Rohan', 'info': {'age': 19, 'course': 'B.Tech'}}
Accessing Values in Nested Dictionaries
To access values in a nested dictionary, we can use multiple square brackets "[]".
Example:
student = {
'name': 'Rohan',
'info': {
'age': 19,
'course': 'B.Tech'
}
}
value = student['info']['course']
print(value)
In above example, we use 'student['info']['course']' to access the course from the info dictionary inside the student dictionary.
Output:
B.Tech
Modifying Nested Dictionary Values
We can modify the values of nested dictionary just like a normal dictionary.
Example:
student = {
'name': 'Rohan',
'info': {
'age': 19,
'course': 'B.Tech'
}
}
student['info']['course'] = 'MBA'
print(student)
Output:
{'name': 'Rohan', 'info': {'age': 19, 'course': 'MBA'}}
Iterating Through Nested Dictionaries
We can use nested loops to iterate through nested dictionaries and access values.
Example:
student = {
'name': 'Rohan',
'info': {
'age': 19,
'course': 'B.Tech'
}
}
for key, value in student.items():
if isinstance(value, dict):
for i, j in value.items():
print(i, j)
else:
print(key, value)
Output:
{'name': 'Rohan', 'info': {'age': 19, 'course': 'MBA'}}