Loop Through a Dictionary in Python
Loop Through the Keys of a Dictionary
A for loop over a dictionary goes through its keys, one at a time, in the order they were added. Inside the loop, d[key] gives you the value that goes with each key.
Think of it like a waiter reading the menu card from top to bottom: each dish name is a key, and the price next to it is the value.
prices = {"tea": 15, "coffee": 25, "juice": 40}
for item in prices:
print(item, "costs", prices[item])tea costs 15 coffee costs 25 juice costs 40
The rules
for key in d:gives you the keys, not the values and not the pairs.- The order is the order the keys were added, so the output is always the same.
- Use
d[key]inside the loop to get the value. The key is surely there, so no KeyError. - Name the loop variable after what the keys are:
item,name,word.
keys() says the same thing
d.keys() gives the keys too. for item in prices.keys(): works exactly like for item in prices:. The short version is more common, but some people like how clearly keys() reads:
ages = {"Sunny": 25, "Rocky": 30}
for name in ages.keys():
print(name)Sunny Rocky
Combine with if
An if inside the loop picks out some of the pairs, like the counting loops of chapter 10:
prices = {"tea": 15, "coffee": 25, "juice": 40}
for item in prices:
if prices[item] > 20:
print(item)coffee juice
Avoid: adding or removing keys while you loop
ages = {"Sunny": 25, "Rocky": 30}
for name in ages:
ages["Lucky"] = 22RuntimeError: dictionary changed size during iteration
Python stops the loop when the dictionary grows or shrinks under it. Changing the value of an existing key is fine. To remove keys, collect them in a list first, then remove them after the loop.
for key in d:goes through the keys in order;d[key]gives each value.