Nested Dictionaries
When a dictionary holds other dictionaries, we call them nested dictionaries.
Example
Build one dictionary with three dictionaries inside it:
Prompt
Write a Python program that creates a nested dictionary called myfamily with three children. Each child (child1, child2, child3) has a name and year: Emil 2004, Tobias 2007, Linus 2011. Print the dictionary.
Output: complete Python program
main.py
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
print(myfamily)
Example
Define three separate dictionaries first, then place them inside a fourth:
Prompt
Write a Python program that creates three separate dictionaries (child1, child2, child3) with name and year for Emil 2004, Tobias 2007, and Linus 2011. Then create a nested dictionary called myfamily containing these three dictionaries. Print the result.
Output: complete Python program
main.py
child1 = {
"name" : "Emil",
"year" : 2004
}
child2 = {
"name" : "Tobias",
"year" : 2007
}
child3 = {
"name" : "Linus",
"year" : 2011
}
myfamily = {
"child1" : child1,
"child2" : child2,
"child3" : child3
}
print(myfamily)
Access Items in Nested Dictionaries
To reach an item in a nested dictionary, chain the dictionary names together, beginning with the outermost one:
Example
Print the name stored for child 2:
Prompt
Write a Python program that creates a nested dictionary called myfamily with three children (child1, child2, child3) each having name and year. Access and print the name of child2.
Output: complete Python program
main.py
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
print(myfamily["child2"]["name"])
Loop Through Nested Dictionaries
The items() method lets you walk through a dictionary, as shown here:
Example
Visit every key and value at both levels of nesting:
Prompt
Write a Python program that creates a nested dictionary called myfamily with three children. Loop through the nested dictionary and print each child's key, followed by all key-value pairs of that child.
Output: complete Python program
main.py
myfamily = {
"child1" : {
"name" : "Emil",
"year" : 2004
},
"child2" : {
"name" : "Tobias",
"year" : 2007
},
"child3" : {
"name" : "Linus",
"year" : 2011
}
}
for x, obj in myfamily.items():
print(x)
for y in obj:
print(y + ':', obj[y])