Looping Over a Dictionary
A for loop can go through a dictionary too. In each iteration, the loop variable gets one key, in the order in which the pairs were added. You read the value that belongs to it with square brackets, with the key in a variable, as in the previous exercise:
capitals = {"Czechia": "Prague", "Slovakia": "Bratislava", "Austria": "Vienna"}
for country in capitals:
print(country, "-", capitals[country])Czechia - Prague
Slovakia - Bratislava
Austria - ViennaIn the first iteration, country holds "Czechia", so capitals[country] is "Prague". In the second iteration, it holds "Slovakia", and so on.
When you need both the key and the value, there's a handier way: the method .items(). It gives the loop the dictionary's pairs, one at a time, and you write two variables after for, separated by a comma. The first one gets the key, the second one the value:
capitals = {"Czechia": "Prague", "Slovakia": "Bratislava", "Austria": "Vienna"}
for country, capital in capitals.items():
print(f"The capital of {country} is {capital}.")The capital of Czechia is Prague.
The capital of Slovakia is Bratislava.
The capital of Austria is Vienna.You choose the names of the two variables. Pick names that say what's in them: for country, capital in ... tells you more than for key, value in ....
The patterns from the lesson on loops work here too. When the values are numbers, you can add them up, or pick some of the pairs with if:
stock = {"apples": 12, "lemons": 0, "pears": 5}
total = 0
for fruit, count in stock.items():
total += count
if count == 0:
print("Sold out:", fruit)
print("Pieces in total:", total)Sold out: lemons
Pieces in total: 17A typical mistake is to forget .items(): for country, capital in capitals:. The loop then gets only the keys, and Python tries to split each key, for example the text "Czechia", into the two variables, one letter into each. There are too many letters, so the program ends with ValueError: too many values to unpack (expected 2).
Instructions
Write a for loop with .items() that goes through scores and prints each player's name and points, separated by a colon, for example Anna: 12.
Below it, in a second loop, print the names of the players who have at least 10 points, each on its own line.
Start programming for free
5/9