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 overWhen it fits
The keysWhen the names themselves matter
The valuesWhen the computation is on the content alone
The pairsWhen 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

  1. Going over the keys gives a name alone.
  2. Then each name’s value is asked for.
  3. That is an extra request each round.
  4. Going over the pairs gives both at once.

Example 2 — an average as a familiar pattern

  1. A accumulator is initialised to zero before the loop.
  2. Each value is added inside it.
  3. It is divided by the dictionary’s length after it.
  4. Exactly the same code as on a list.
Going over pairs: a name and a value each round, and the accumulator pattern works unchanged.