Codiqo

Learn Python · lesson 31 of 60 · about 7 minutes

Nested Data

Plan the week: keep a list of things for each day in a dictionary, find the busiest day, and read the day the planner asked about.

What you'll learn

  • Put dictionaries inside lists
  • Read nested values
  • Pick a list, tuple, set or dict

A plan for the week

Each day of Sam's week has its own list of things to do: swimming on Monday, piano and homework on Wednesday, nothing on Tuesday. That's a dictionary of lists: the key is the day and the value is that day's list. The assistant loops over items() to find the busiest day, and shows the plan for the day number the planner asked about in the last unit, with get giving an empty list for days that aren't in the plan.

Collections inside collections

Real data is often a list of records, where each record is a dictionary. Read nested values one step at a time: first the list index, then the key.

A class register

students = [
    {"name": "Ada", "scores": [9, 7]},
    {"name": "Bo", "scores": [6, 8]},
]
print(students[1]["name"])
print(students[0]["scores"][1])
for s in students:
    print(s["name"], sum(s["scores"]))

Output

Bo
7
Ada 16
Bo 14

Choosing a structure

| need | use |
|---|---|
| ordered, changeable items | list |
| fixed group of values | tuple |
| unique values | set |
| look up by name | dict |

Tip

To find the biggest, start with a value nothing can be smaller than, like -1 for a count, and replace it whenever a bigger one turns up. A day with an empty list still has a count of 0, which beats -1.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.