Python Nested Dictionaries
A nested dictionary is a dictionary stored as a value in another dictionary.
A dictionary of dictionaries
Each student name points to a whole dictionary.
students = {"Ada": {"maths": 90, "english": 85}, "Bob": {"maths": 78, "english": 88}}
print(students)Get one inner dictionary
One key gives the inner dictionary for Ada.
students = {"Ada": {"maths": 90, "english": 85}, "Bob": {"maths": 78, "english": 88}}
print(students["Ada"])Reach a deep value
Use two keys in a row. The first picks the student, the second picks the subject.
students = {"Ada": {"maths": 90, "english": 85}, "Bob": {"maths": 78, "english": 88}}
print(students["Bob"]["english"])Add a whole sub-dictionary
Assign a full dictionary to a new outer key.
students = {"Ada": {"maths": 90, "english": 85}, "Bob": {"maths": 78, "english": 88}}
students["Cy"] = {"maths": 95, "english": 81}
print(students["Cy"])Example
register = {"Ada": {"maths": 91, "english": 84}, "Bob": {"maths": 76, "english": 89}}
score = register["Ada"]["maths"]
print(f"Ada maths: {score}")Key points
- Nested dictionary: a dictionary stored as a value in another dictionary.
- Use chained [ ] to reach a deep value, one key at a time.
- Add a whole sub-dictionary with one assignment to a new outer key.
- Use nesting when one thing owns a small group of facts.
- Flat keys like "Ada_maths" get messy when each student has many subjects.
- A missing key raises KeyError, just like a flat dictionary.
In this example, register holds two students. Each student value is a dictionary of subjects and scores. The code reads register["Ada"] first. That gives Ada's inner dictionary. It then reads ["maths"] from that dictionary. The score is 91, and the f-string prints it.
Note
Each step of a chained [ ] must exist.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
How do you read Bob's english score from students?