Grade 8 Computer Science · Dictionaries
Structures inside structures
A list of dictionaries, and a dictionary of lists — and how not to get lost.
A chain of accesses, and an error with no address
One line reaches a student’s score through a list, a dictionary and another list. When it breaks, the message points at the whole line and does not reveal at which stage. There is one simple question that repeats at every stage, and it makes the chain readable.
Real data is almost never flat. A class is a list of students, each student is a dictionary of fields, and one of its fields is a list of marks. That sounds complicated, and it is exactly the same two structures already known — only nested.
students = [
{"name": "Ana", "scores": [90, 85]},
{"name": "Ben", "scores": [70, 95]},
]
print(students[0]["name"])
print(students[1]["scores"][0])| After the step | What is in hand |
|---|---|
| An item was taken from the list | A student’s dictionary |
| The marks key was asked for | A list of numbers |
| An item was taken from that list | A single number |
Why breaking it into lines helps
A long chain of accesses in one line works, and it is very hard to locate a mistake in it: if something breaks in the middle, the message points at the whole line and does not say at which stage. Saving each stage in a variable with a meaningful name turns the chain into four lines, and each of them can be checked separately. It is also far more readable to whoever reads after you — and it is exactly the same consideration seen when we broke a program into functions: one breaks things up so they are easy to understand and locate, not so they are short.
Example 1 — reading layer by layer
- Start with a list of students.
- An item from it is a dictionary.
- A key in it is a list of marks.
- An item from it is a single number.
Example 2 — locating a mistake in a chain
- The chain breaks and there is no telling where.
- It is broken into lines with names.
- What is in hand is printed at each stage.
- The stage where the value surprises is the problem.