🗂️ Dictionaries & Sets, lesson 3 of 5
Nested data: records and groups
Combine lists and dicts to model real-world data.
10 min
1 exercise
2 quizzes
0/3 solved
Getting Python ready… examples can run in a moment.
Real data is usually nested:
- a list of dicts: many records with the same fields (books, users, orders)
- a dict of lists: a group of values per key (marks per student, tasks per day)
Chain the lookups: books[0]["title"].
A list of records
Add a fourth book. Inside an f-string, use single quotes for the keys.
Grade book: a dict of lists
gradebook["Ana"] is a list, so you can call .append on it directly.
What does this print?
Grouping is the counting pattern's big sibling:
start each new key with an empty list, then append.
d.setdefault(key, []) does both steps in one go:
it returns the existing list, or inserts and returns
a new empty one.
Group contacts by city
Add ("Eli", "Oslo") to people and run it again.
Merge settings
a | b makes a new merged dict (b wins on
clashes). a.update(b) changes a in place.
What does this print?
Class averages
- Fill
averagesso it maps each student's name to the average of their marks. - Set
top_studentto the name with the highest average.