Loop over keys and values
prices = {"apple": 3, "pear": 2}
for fruit, price in prices.items():
print(fruit, price)
# apple 3
# pear 2
items() hands you each key-value pair, which you unpack into two variables.
Loop over keys only
for fruit in prices:
print(fruit) # apple, pear
Looping over the dictionary directly gives you its keys, so there is no need to write .keys().
Loop over values only
for price in prices.values():
print(price) # 3, 2
Use .values() when you only care about the values and not the keys.
Common mistakes
- Forgetting to unpack.
for item in d.items()gives you a tuple — writefor key, value in d.items()instead. - Changing the dictionary while looping. Adding or removing keys mid-loop raises an error; iterate over a copy like
list(d.items())if you must.
Frequently asked questions
What order does the loop follow?
Since Python 3.7, dictionaries preserve insertion order, so you iterate in the order items were added.
How do I loop with an index too?
Wrap the loop in enumerate(): for i, (key, value) in enumerate(d.items()):.
Loops and dictionaries are core skills — build them up with our free Python course.