Python Nested Dictionaries
A dictionary in Python can contain other dictionaries. This concept is known as nested dictionaries, allowing you to structure complex data hierarchies.
Example 1: Creating Nested Dictionaries
To create a dictionary containing other dictionaries, you can define it as follows:
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
Example 2: Adding Dictionaries to Another Dictionary
Alternatively, you can create multiple dictionaries and add them to a new one:
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
Accessing Items in Nested Dictionaries
To access data from a nested dictionary, you simply use the keys of the outer and inner dictionaries:
print(myfamily["child2"]["name"])
Looping Through Nested Dictionaries
You can loop through a dictionary using the items() method to access both keys and values:
for x, obj in myfamily.items():
print(x)
for y in obj:
print(y + ':', obj[y])
