Beginner·7 min·basics · data structures
Nested Data
You’ll be able to
- Model real-world data with lists of dicts and dicts of lists
- Navigate deeply nested structures without errors
- Iterate over nested collections with nested loops
- Flatten and restructure nested data safely
Why this matters
Every REST API response is nested JSON, and navigating dicts inside lists inside dicts is a daily task in web and data work. Libraries like requests and pydantic hand back exactly this shape.
Common pitfalls
- Blindly chaining
d['a']['b']['c']. If any key is missing, it raisesKeyError; use.get()chains ordict.get('a', {}).get('b'). - Copying nested dicts with
d.copy(). That is shallow; inner dicts still alias. Usecopy.deepcopy()for true clones. - Assuming JSON keys are always strings. In Python dicts they can be any hashable type, which breaks
json.dumpson int keys.
Real data is almost always nested: lists of records, dicts of dicts.
Access
data[0]["field"]— chain subscripts left to right- Always think about what type each step returns
Useful pattern: dict.setdefault
d.setdefault(key, []).append(x) — start an empty list under key if missing, then append. The bread-and-butter of grouping.
Try it
- Build a list of skills sorted by how many users have them.
- Find users who know
"git".
Practice
3 graded exercises
Write the code, click Check. We’ll tell you exactly what to fix.
Progress0 / 3
- Exercise 1
From this list of users, print the name of the second user (index
1). Expected:Grace. - Exercise 2
From the same
userslist, print the sum of all ages. Expected:120. - Exercise 3
Build a list of just the names of users whose age is at least 40, then print it. Expected:
['Grace', 'Linus'].