Nested Dictionaries
What You'll Learn: In this tutorial, you'll discover how to create and work with nested dictionaries. Nested dictionaries are dictionaries within dictionaries, useful for storing more complex data.
Creating Nested Dictionaries
A nested dictionary is a dictionary that contains other dictionaries.
Example Code:
myfamily = {
"child1": {
"name": "Emil",
"year": 2004
},
"child2": {
"name": "Tobias",
"year": 2007
},
"child3": {
"name": "Linus",
"year": 2011
}
}
Or, you can create multiple dictionaries and then nest them:
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 items from a nested dictionary, you use the names of the dictionaries, starting with the outer dictionary.
Example Code:
# Print the name of child 2
print(myfamily["child2"]["name"])
Output: Tobias
Loop Through Nested Dictionaries
You can loop through a nested dictionary using the items() method.
Example Code:
for x, obj in myfamily.items():
print(x)
for y in obj:
print(y + ':', obj[y])
Output:
child1
name: Emil
year: 2004
child2
name: Tobias
year: 2007
child3
name: Linus
year: 2011Try It Yourself: Fun Exercises
- Create Your Family Tree:
- Make a nested dictionary to represent your family tree, with names and birth years.
- Access and print the name of a specific family member.
- Organize Your School Subjects:
- Create a nested dictionary of your school subjects and the topics covered.
- Loop through the dictionary to print each subject and its topics.
Summary:
In this Python tutorial, we learned how to create and work with nested dictionaries. These include creating nested dictionaries, accessing items, and looping through them. Nested dictionaries are powerful for organizing complex data. Keep experimenting and have fun with nested dictionaries in Python!