Level 1
0 / 100 XP

Looping over dicts

Once your data is in a dict, you'll often want to walk through every entry. Python gives you three clean ways to loop.

Loop over keys

By default, looping over a dict gives you its keys:

Python
prices = {"apple": 2, "banana": 1} for key in prices: print(key) # apple # banana

Loop over values

Use .values() when you only care about the values:

Python
prices = {"apple": 2, "banana": 1} for value in prices.values(): print(value) # 2 # 1

Loop over key–value pairs

Use .items() to get both the key and the value at once:

Python
prices = {"apple": 2, "banana": 1} for key, value in prices.items(): print(key + ": " + str(value)) # apple: 2 # banana: 1

Note the str(value) — you must convert numbers to strings before joining them with +.

Key takeaways

  • Looping a dict directly gives you its keys.
  • .values() loops over values only.
  • .items() gives you (key, value) pairs — use it when you need both.