Grade 8 Computer Science · Dictionaries
Going over a dictionary
Three ways to go over one, and why one chooses among them by what is needed.
What exactly is the loop going over?
In a list, a loop goes over the items and there is nothing to ask. In a dictionary every value also has a name, and suddenly there are three possible answers. One of them does double work without you noticing, and any of them can skip items if the dictionary changes along the way.
A dictionary is not only for a pointed lookup. Often one wants to go over the whole of it: to sum all the values, to find the key with the highest value, or to build another dictionary from it. Here a question arises that does not exist with a list — over what exactly is one going.
ages = {"Ana": 13, "Ben": 14, "Cara": 13}
total = 0
for name, age in ages.items():
total = total + age
print(name, age)
print(total / len(ages))| Going over | When it fits |
|---|---|
| The keys | When the names themselves matter |
| The values | When the computation is on the content alone |
| The pairs | When both are needed together |
All the processing patterns return here
Once one goes over a dictionary in a loop, the four patterns from last year work unchanged: summing with an accumulator starting at zero, counting inside a branch, filtering into a new dictionary, and searching with an early leave. Again it turns out that one idea was learned and not four — this time it works on a data structure that did not exist then. That is a good sign of a deep idea: it keeps working when the surroundings change.
Example 1 — why going over pairs saves
- Going over the keys gives a name alone.
- Then each name’s value is asked for.
- That is an extra request each round.
- Going over the pairs gives both at once.
Example 2 — an average as a familiar pattern
- A accumulator is initialised to zero before the loop.
- Each value is added inside it.
- It is divided by the dictionary’s length after it.
- Exactly the same code as on a list.