Nested data: records and groups

Dictionaries & Sets, lesson 3 of 5

🗂️ 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"].

Example

A list of records

Add a fourth book. Inside an f-string, use single quotes for the keys.

Example

Grade book: a dict of lists

gradebook["Ana"] is a list, so you can call .append on it directly.

Quiz

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.

Example

Group contacts by city

Add ("Eli", "Oslo") to people and run it again.

Example

Merge settings

a | b makes a new merged dict (b wins on clashes). a.update(b) changes a in place.

Quiz

What does this print?

Exercise

Class averages

  1. Fill averages so it maps each student's name to the average of their marks.
  2. Set top_student to the name with the highest average.