Skip to content

Module 8 · Python Data Structures — topic 21 of 22

Nested dictionaries

Dictionaries can hold other dictionaries and lists to represent structured records. Learn to read, update and loop over nested data safely, as you will with JSON from files and APIs.

Beginner 12 min read·Lesson 124 of 306 in Python Programming

Learning objectives

  • Represent records with nested dictionaries
  • Read and update nested values safely
  • Loop over nested structures to build summaries

Definition

Dictionaries can hold other dictionaries and lists to represent structured records. Learn to read, update and loop over nested data safely, as you will with JSON from files and APIs.

Introduction

Real data is rarely flat. A student has a name, a list of marks and an address with its own fields. Nesting dictionaries and lists inside dictionaries lets one structure describe all of it, exactly like the JSON data you get from web APIs.

Why it matters

APIs, configuration files and databases return nested data. Being able to navigate it, pull out the values you need and handle missing pieces gracefully is essential for any project that talks to the outside world.

Detailed explanation

Chain lookups to go deeper: student["address"]["city"]. Each step returns the inner value, which you index further.

Mix dictionaries and lists freely: data["students"][0]["marks"][2] means the third mark of the first student.

Any missing key along the chain raises KeyError. Use get() with an empty dictionary as the default for optional levels: student.get("address", {}).get("city", "unknown").

Updating works the same way: student["address"]["city"] = "Mumbai" changes the inner dictionary in place.

Loop over nested structures with nested loops, usually items() at the outer level.

Keep the shape consistent: if every record has the same keys, code that reads them stays simple.

Printing deeply nested data is easier with json.dumps(data, indent=2) or pprint, covered in later modules.

Syntax

Python
city = data["address"]["city"]
city = data.get("address", {}).get("city", "unknown")
data["marks"]["maths"] = 90
  • Chain [] to reach inner values.
  • Use get() with {} for optional levels.
  • Assign to an inner key to update it.

Code examples

Reading nested values

Python
student = {
"name": "Asha",
"marks": {"maths": 82, "physics": 91},
"address": {"city": "Pune", "pin": "411001"},
}
print(student["marks"]["physics"])
print(student["address"]["city"])
print(len(student["marks"]))
Output
91
Pune
2

Safe access

Python
student = {"name": "Ben", "marks": {"maths": 67}}
print(student.get("address", {}).get("city", "unknown"))
print(student["marks"].get("physics", "not taken"))
Output
unknown
not taken

More examples

A class report from nested data

Python
school = {
"class": "10-A",
"students": {
"Asha": {"marks": {"maths": 82, "science": 91}, "city": "Pune"},
"Ben": {"marks": {"maths": 67, "science": 74}, "city": "Delhi"},
"Chen": {"marks": {"maths": 95, "science": 88}, "city": "Pune"},
},
}
print("Class", school["class"])
for name, info in school["students"].items():
marks = info["marks"]
avg = sum(marks.values()) / len(marks)
print(f"{name:<5} avg {avg:.1f} from {info['city']}")
school["students"]["Ben"]["marks"]["maths"] = 70
by_city = {}
for name, info in school["students"].items():
by_city.setdefault(info["city"], []).append(name)
print(by_city)
print("Ben maths now:", school["students"]["Ben"]["marks"]["maths"])
Output
Class 10-A
Asha  avg 86.5 from Pune
Ben   avg 70.5 from Delhi
Chen  avg 91.5 from Pune
{'Pune': ['Asha', 'Chen'], 'Delhi': ['Ben']}
Ben maths now: 70

Step-by-step explanation

  • school["students"] is a dictionary keyed by name; each value is another dictionary.
  • items() gives each student’s name and info; info["marks"] is a third-level dictionary.
  • The chained assignment updates one mark deep inside the structure.
  • setdefault groups names by city into lists.

Expected output

Running “A class report from nested data” prints exactly:

TextOutput
Class 10-A
Asha avg 86.5 from Pune
Ben avg 70.5 from Delhi
Chen avg 91.5 from Pune
{'Pune': ['Asha', 'Chen'], 'Delhi': ['Ben']}
Ben maths now: 70

Practical applications

  • Weather and payment APIs return nested JSON that becomes nested dictionaries.
  • Configuration files describe settings in nested sections.
  • E-commerce orders contain customer, address and item details nested together.

Best practices

  • Keep nested records consistent.
  • Use get() for optional levels.
  • Extract deep values into well-named variables before using them.

Common mistakes

Assuming every level exists

Avoid

city = user["address"]["city"]

Prefer

city = user.get("address", {}).get("city")

A missing address raises KeyError; get() handles optional parts.

Inconsistent record shapes

Avoid

Some records use "mark", others "marks".

Prefer

Agree on one shape and validate incoming data.

Mixed shapes force special cases everywhere in the code.

Key takeaways

  • Nested dictionaries and lists represent structured records.
  • Chain lookups to reach inner values; get() avoids KeyError.
  • Loop with items() and nested loops to summarise.

Try it yourself

  1. 1
    Model a book with title, author (name and country) and a list of ratings, then print the average rating.
  2. 2
    Write code that prints each student’s highest subject from the school dictionary above.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

13 questions cover the “Python Data Structures” module. Answers and explanations are revealed after you submit.

  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
  • BeginnerWhat is printed?
Practise this module