Lists and Dictionaries

Looping over a dictionary

Follow a loop that visits every key in a dictionary, looks each value up, and leaves a total or a count behind.

A dictionary you have to name every key of by hand is not much better than a set of separate variables. What makes it worth having is that a program can go through the whole of one without knowing in advance what is in it — a shop's stock list works the same way whether it holds four things or four hundred. A loop written "for name in stock:" makes one trip for every pair, and each trip hands you one of the keys. Python goes through them in the order the pairs were put in, so a dictionary written out in a program is walked left to right, exactly as it reads.

The loop gives you keys — the values are one step further on

This is the mistake to watch for, and it is easy to make because the loop over a list does not have this shape. There, the variable held the values themselves and there was nothing further to do. Here, the variable holds a key, and the value is whatever that key looks up to, so a total that is meant to add the values has to say stock[name] rather than name. Writing name there does not add up the wrong numbers — it usually stops the program outright, because a key like "pen" is a piece of writing and there is nothing sensible to add it to a total.

Worked example

By how much does the largest of these readings differ from the smallest?

temps = {"morning": 16, "noon": 29, "night": 11}
  1. Go through the values on their own — 16, 29 and 11 — and pick out the largest, which is 29.

    A loop looking for the largest would do the same walk: hold on to the best so far, and replace it whenever something beats it.

Try it together

Now a loop that runs over one dictionary and looks in two.

before = {"pen": 4, "bag": 9, "cup": 2}
after = {"pen": 7, "bag": 9, "cup": 5}
up = 0
for name in before:
    if after[name] > before[name]:
        up = up + 1
print(up)

The loop heading names only one of the two dictionaries, but both of them have the same three keys, so a key from one can be used in the other.

    1.On the first trip round, name holds the first key. What number does after[name] give on that trip?

    Have a go

    Have a go on your own. What is the first number this program prints?

    levels = {"low": 2, "high": 8}
    for name in levels:
        print(levels[name] + 1)

    Ready to practice?

    Eight questions on what you have just read. Nothing is timed, and you can play as many times as you like.

    Print a worksheet