the full guide

Nested dictionaries

A nested dictionary is a dictionary whose values are themselves dictionaries or lists. It's how Python represents structured data like JSON.

6 min Intermediate

What you need: The earlier topics of this module.

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

nested.py
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

Question 1

1. d = {"a": {"b": 1}}. How do you get 1?

Question 2

2. What does {}.get("x") return?

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