Definition
A nested dictionary is a dictionary whose values are themselves dictionaries or lists. It's how Python represents structured data like JSON.
In simple words
An academy's register: the academy has batches, a batch has students, and a student has marks. Each level is a dict inside a dict, and you open them one key at a time.
Why it matters
API responses, config files and LLM tool calls all arrive as nested JSON, so you'll read these all the time.
How it works
In code
academy = {
"batch_a": {
"Riya": {"maths": 91, "science": 88},
"Aman": {"maths": 76},
},
}
print(academy["batch_a"]["Riya"]["maths"])
print(academy["batch_a"]["Aman"].get("science", "absent"))
academy["batch_a"]["Sara"] = {"maths": 95}
for student, marks in academy["batch_a"].items():
print(student, "best:", max(marks.values()))Output
91 absent Riya best: 91 Aman best: 76 Sara best: 95
Common mistakes
- Using [] on a key that might be missing, which raises KeyError.
- Shallow-copying a nested dict and then editing the inner part. Both copies change. Use copy.deepcopy.
Check yourself
Summary
- Dicts inside dicts hold structured data.
- Use .get() for keys that may be absent.
- Use deepcopy to copy nested data safely.
Finished reading?
Sources: The Python Tutorial, python.org