Loop Over a Dictionary with items()
To loop over a dictionary with items(), write for key, value in scores.items():. Each turn of the loop gives you one key and its value together.
Before this lesson you should know how to make a dictionary and loop over its keys: see Dictionaries.
Get each key and value together
.items() gives the dictionary's pairs. Put two names after for, with a
comma between them:
prices = {"apple": 2, "pear": 3, "plum": 1}for fruit, price in prices.items(): print(fruit, price)It printed apple 2, pear 3, then plum 1. On each turn fruit holds a
key and price holds that key's value.
The key comes first, the value second
The first name always gets the key and the second name gets the value. Pick names that say what each one holds:
ages = {"Ada": 12, "Ben": 9}for name, age in ages.items(): print(name) print(age)It printed Ada, 12, Ben, then 9. The pairs come in the order they were
added to the dictionary.
No lookup needed
Looping over the keys alone needs a lookup, ages[name], to get each value.
With .items() the value is already there. These two loops print the same
lines:
ages = {"Ada": 12, "Ben": 9}for name in ages: print(name, ages[name])for name, age in ages.items(): print(name, age)Both loops printed Ada 12 and Ben 9. The second one never writes
ages[...].
Use the value in the loop body
The value is an ordinary variable inside the loop. You can compare it or do sums with it:
stock = {"pens": 0, "books": 4, "maps": 7}for thing, count in stock.items(): if count > 0: print(thing, count * 2)It printed books 8, then maps 14. pens was skipped, because its count is
0.
See also: Dictionaries, Unpacking Values.
Your turn
Add two lines: loop over heights.items() and print each name with its height.
Mia 150 Leo 142
heights = {"Mia": 150, "Leo": 142}# add a for loop over heights.items() that prints each name and height