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.
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
- Chain [] to reach inner values.
- Use get() with {} for optional levels.
- Assign to an inner key to update it.
Code examples
Reading nested values
91 Pune 2
Safe access
unknown not taken
More examples
A class report from nested data
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: 70Step-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:
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
Prefer
A missing address raises KeyError; get() handles optional parts.
Inconsistent record shapes
Avoid
Prefer
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
- 1Model a book with title, author (name and country) and a list of ratings, then print the average rating.
- 2Write 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?