Skip to main content

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

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

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

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