How do I loop over a dictionary's keys and values in Python?
Short answer
Loop with .items() to get keys and values together, .keys() for keys, or .values() for values. Iterating the dictionary directly gives keys, which trips up people expecting pairs.
The short version
Use .items() to get the key and value together in each iteration, .keys() for keys alone, and .values() for values alone. Looping over the dictionary directly yields its keys, not key-value pairs, which is the point people most often get wrong.
The usual case: both at once
prices = {"pen": 2, "mug": 5, "cup": 4}
for name, price in prices.items():
print(name, price)
.items() yields a (key, value) pair each time, and the two-name unpacking on the left splits it into name and price.
Keys only
Iterating the dictionary itself gives keys, so these two loops are identical.
for name in prices:
print(name)
for name in prices.keys():
print(name)
Writing .keys() is slightly more explicit about intent, but plain iteration is common and fine.
Values only
for price in prices.values():
print(price)
The mistake to recognise
People sometimes expect direct iteration to give pairs and write this:
for name, price in prices: # ValueError
...
This raises ValueError: too many values to unpack, because each item is a single key string, not a pair. The fix is .items().
Order is insertion order
Since Python 3.7, dictionaries keep the order you inserted keys, so these loops are predictable and repeatable. You do not need an OrderedDict just to preserve order any more.
Modifying while looping
Do not add or remove keys during iteration, because it raises RuntimeError: dictionary changed size during iteration. If you need to delete some keys, collect them first, then remove them afterwards, or build a new dictionary with a comprehension.
prices = {k: v for k, v in prices.items() if v > 3}