Python Loop Dictionaries

Looping through a dictionary lets you visit every key, value, or pair, which is essential for reading and processing stored data.

Looping over keys

A plain for loop over a dictionary walks through its keys. You can then use each key to look up its value inside the loop body.

Iterating keys

prices = {"apple": 3, "banana": 1, "cherry": 5}

for fruit in prices:
    print(fruit, "costs", prices[fruit])

Looping over values and pairs

When you only care about the values, loop over values(). When you need both at once, items() gives you each key and value together, which you can unpack into two loop variables.

values() and items()

prices = {"apple": 3, "banana": 1, "cherry": 5}

for amount in prices.values():
    print(amount)

for fruit, amount in prices.items():
    print(fruit, "->", amount)
Note: Unpacking with 'for key, value in my_dict.items()' is the clearest and most common way to loop when you need both parts of each pair.

Choosing what to iterate

Loop formLoop variable holds
for k in dEach key
for k in d.keys()Each key (explicit)
for v in d.values()Each value
for k, v in d.items()Each key and its value

A practical example

Summing the values

prices = {"apple": 3, "banana": 1, "cherry": 5}

total = 0
for amount in prices.values():
    total += amount

print("Total:", total)  # Total: 9
  • Looping the dictionary directly yields keys.
  • Use values() to work only with values.
  • Use items() to get keys and values in the same loop.
  • Avoid adding or deleting keys while looping, as it can raise a RuntimeError.