What a dictionary loop does
A for loop can visit every entry of a dictionary, one at a time. The loop body runs once per key. There are two ways to write it, and they differ in what the loop variables hold.
Keys and values together: items()
scores.items() hands the loop each key with its value. Give the loop two variables: the key comes first, the value second.
scores = {"Ana": 12, "Ben": 7, "Cleo": 15, "Dan": 9}
for name, points in scores.items():
print(name, points)
Ana 12
Ben 7
Cleo 15
Dan 9
Each turn of the loop receives a pair such as ("Ana", 12), and Python unpacks it into name and points. With a single variable you get the whole pair as a tuple.
Keys only: the dictionary itself
A loop over the dictionary gives only the keys. You can still read each value with the key:
for name in scores:
print(name, scores[name])
This prints the same four lines. Use items() when you need both, because it reads more clearly than looking each value up again.
Other ways to look at a dictionary
Two more views are handy. scores.keys() gives only the keys and scores.values() gives only the values. For the exercise's dictionary, list(scores.keys()) is ['Ana', 'Ben', 'Cleo', 'Dan'] and list(scores.values()) is [12, 7, 15, 9]. When only the values matter, as in a plain total, for points in scores.values(): is enough. The exercise also needs a count of players, but it needs no names, so that loop could use .values() too.
Order
Python keeps the keys in the order they were added, so the loops above print Ana, Ben, Cleo, Dan. Many other languages make no such promise. When the answer is a total or a count, the order cannot change it, so those are safe results to compute in a loop.
Traps
- Two variables over the dictionary itself.
for a, b in scores:tries to split each key, a string, into two parts, and stops withValueError: too many values to unpack (expected 2). Add.items(). - Changing the keys during the loop. Adding or deleting a key inside the loop stops the program with
RuntimeError: dictionary changed size during iteration. Collect what you want to change first, and change the dictionary after the loop. Changing the value of an existing key is allowed. - Mixing up the order of the variables.
for points, name in scores.items()is legal, butpointsnow holds the keys.
The exercise, step by step
The dictionary scores maps each player to their points. The task: add up all the points in total, and count in count the players with 10 points or more.
- Write
for name, points in scores.items():below the line that setscountto 0. - Inside the loop, add
pointstototal. - Still inside, if
pointsis 10 or more, add 1 tocount.
scores = {"Ana": 12, "Ben": 7, "Cleo": 15, "Dan": 9}
total = 0
count = 0
for name, points in scores.items():
total += points
if points >= 10:
count += 1
print(total)
print(count)
The output is:
43
2
The total is 12 + 7 + 15 + 9 = 43. Ana (12) and Cleo (15) reach 10, so the count is 2. The variable name is never used here, which is fine: the loop still needs a place to put the key.
Key takeaways
for key, value in d.items():visits every key with its value.for key in d:visits only the keys; read the value withd[key].- Python dictionaries remember insertion order, but totals and counts do not depend on it.
- Do not add or delete keys while looping.
