Python Program to Work with a Nested Dictionary
Intermediate · Dictionaries
A nested dictionary is a dictionary whose values are themselves dictionaries, which is how you store records with several fields, like each student with their class and marks. This program reads, changes, adds and loops through values at every level.
Program
Riya is in class 11
Arjun's Physics mark: 81
Riya (class 11): {'Maths': 90, 'Physics': 92}, average 91.0
Arjun (class 12): {'Maths': 75, 'Physics': 81, 'Chemistry': 70}, average 75.3
Meera (class 11): {'Maths': 95, 'Physics': 89}, average 92.0How it works
- Each key of
schoolis a student, and its value is another dictionary with the keys "class" and "marks"; "marks" is a third dictionary inside that. - Square brackets are chained to go deeper:
school["Arjun"]["marks"]["Physics"]means Arjun, then his marks, then Physics. - Assigning to a chained key changes the value if the key exists and adds it if it does not, which is how Chemistry is added for Arjun.
- A whole new student is added by assigning a complete inner dictionary to a new key.
- The loop takes each student and their inner dictionary with
items(), then works out the average of their marks.
Other ways to write it
Reading safely with get()
Kabir's marks: no record Riya's Physics: not taken
Each get() returns a default instead of failing, and using {} as the default for the outer level lets the next get() still work.
Copying a nested dictionary
Original: {'Riya': {'Maths': 50}}
Shallow copy: {'Riya': {'Maths': 50}}
Deep copy: {'Riya': {'Maths': 88}}copy() copies only the outer dictionary, so both share the same inner dictionaries and see each other's changes. copy.deepcopy() copies every level, giving a truly separate dictionary.
Try it yourself
Add a "Biology" mark for Meera and check that her average changes.
Edit the program above and press Run, or open it in the full editor to save it and share it. To watch it run line by line, open it in the visualizer.
Related programs
- Make a Simple Phone Book
- Store Student Records Using a Class
- Find the Sum of All Values in a Dictionary
- Read and Write a JSON File
- Find Students Who Scored Above 75 Using a Dictionary
- Merge Two Dictionaries
- Sort a Dictionary by Value
- Sort a Dictionary by Key
- Check if a Key Exists in a Dictionary
- Create a Dictionary from Two Lists
All Python programs · CBSE class 12 practical file · Python exercises