Editor

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

nested_dictionary.py
school = {
"Riya": {"class": 11, "marks": {"Maths": 88, "Physics": 92}},
"Arjun": {"class": 12, "marks": {"Maths": 75, "Physics": 81}},
}
# Read values two and three levels deep
print("Riya is in class", school["Riya"]["class"])
print("Arjun's Physics mark:", school["Arjun"]["marks"]["Physics"])
# Change a value, and add a new subject
school["Riya"]["marks"]["Maths"] = 90
school["Arjun"]["marks"]["Chemistry"] = 70
# Add a whole new student
school["Meera"] = {"class": 11, "marks": {"Maths": 95, "Physics": 89}}
# Loop through every student and their marks
for name, info in school.items():
marks = info["marks"]
average = sum(marks.values()) / len(marks)
print(f"{name} (class {info['class']}): {marks}, average {average:.1f}")
Output
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.0

How it works

  1. Each key of school is a student, and its value is another dictionary with the keys "class" and "marks"; "marks" is a third dictionary inside that.
  2. Square brackets are chained to go deeper: school["Arjun"]["marks"]["Physics"] means Arjun, then his marks, then Physics.
  3. 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.
  4. A whole new student is added by assigning a complete inner dictionary to a new key.
  5. 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()

Reading safely with get()
school = {"Riya": {"class": 11, "marks": {"Maths": 88}}}
# school["Kabir"]["marks"] would raise a KeyError
print("Kabir's marks:", school.get("Kabir", {}).get("marks", "no record"))
print("Riya's Physics:", school["Riya"]["marks"].get("Physics", "not taken"))
Output
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

Copying a nested dictionary
import copy
original = {"Riya": {"Maths": 88}}
shallow = original.copy()
deep = copy.deepcopy(original)
original["Riya"]["Maths"] = 50 # change the inner dictionary
print("Original: ", original)
print("Shallow copy:", shallow) # changed too
print("Deep copy: ", deep) # still 88
Output
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.

All Python programs · CBSE class 12 practical file · Python exercises