Python Iterating Through Dictionaries

In the last lesson you learned Dictionary Comprehensions, a quick way to build a dictionary in one line. But once you have a dictionary full of data, you need a way to walk through it and look at everything inside. That walking through is what we call iterating. And that is what this lesson is about.

πŸ€” Why Loop Over a Dictionary?

Say you have a dictionary of products and their prices. You want to print each product with its price. You could pull out one item at a time by hand. But what if there are fifty products? Typing each one out is slow and tiring.

A loop solves this. A loop is a way to repeat the same action for every item in a collection. So you write the printing code once. Then Python runs it for every product on its own.

Here is the thing. A dictionary holds two pieces for each entry: a key and a value. So when you loop, you get to decide what you want back. Just the keys? Just the values? Or both together? Python gives you a clean way to ask for each one.

πŸ”‘ Looping Gives You Keys by Default

When you put a dictionary straight into a for loop, Python hands you the keys, one at a time. Not the values. Just the keys.

Here is a small dictionary of products and their prices. We loop over it directly and print whatever the loop gives us.

prices = {"apple": 30, "banana": 10, "mango": 50}
for product in prices:
print(product)

The loop variable product gets each key in turn. So the output is the product names, not the prices.

Output

apple
banana
mango

Now here is the useful part. Once you have a key, you can look up its value with square brackets. So you can still reach the price even though the loop only gave you the key.

prices = {"apple": 30, "banana": 10, "mango": 50}
for product in prices:
print(product, "costs", prices[product])

For each key, prices[product] fetches the matching price. So now each line shows the name and its price together.

Output

apple costs 30
banana costs 10
mango costs 50

Note

Looping the dictionary directly is the same as looping prices.keys(). Python just treats the dictionary itself as its keys when you iterate. So for product in prices and for product in prices.keys() do exactly the same thing.

πŸ’° Looping Over Values with .values()

Sometimes you do not care about the keys at all. You only want the values. Maybe you want to add up every price. Or find the most expensive one. For that, Python gives you .values().

The .values() method hands you each value in the dictionary, one at a time, and skips the keys entirely.

Here we loop over just the prices and add them all into a total.

prices = {"apple": 30, "banana": 10, "mango": 50}
total = 0
for price in prices.values():
total = total + price
print("Total:", total)

We start total at zero. Then for each price the loop gives us, we add it onto the total. After the loop finishes, we print the final sum.

Output

Total: 90

So when the keys do not matter and you only need the data, .values() is the clean choice.

🀝 Looping Over Both with .items()

Most of the time you want both the key and its value together. Looking up prices[product] inside the loop works fine. But there is a nicer way that reads more clearly.

The .items() method gives you both pieces at once: the key and the value, paired up. You catch them in two loop variables instead of one.

Here we loop over the products and prices together and print each pair.

prices = {"apple": 30, "banana": 10, "mango": 50}
for product, price in prices.items():
print(f"{product} costs {price}")

Notice the two names after for: product and price. On each turn, product gets the key and price gets the value, both from the same entry. Then the f-string drops them into one clean line.

Output

apple costs 30
banana costs 10
mango costs 50

This is the pattern you will reach for most. It reads almost like plain English. And you never have to look the value up by hand.

Here is the same idea in a more real example. We have a cart of items and we want a neat receipt with a running total.

cart = {"Notebook": 45, "Pen": 12, "Eraser": 8}
print("Your receipt:")
total = 0
for item, price in cart.items():
print(f"{item:<10} ${price}")
total = total + price
print("-" * 15)
print(f"{'Total':<10} ${total}")

We loop over the cart with .items(), so we get each item name and its price together. We print each one in a tidy column and keep adding to the total. At the end we print a line and the final total.

Output

Your receipt:
Notebook $45
Pen $12
Eraser $8
---------------
Total $65

πŸ“‹ Quick Comparison

Here is a quick way to remember which method gives you what.

What you write What the loop gives you Use it when
for k in d each key you only need the keys
for k in d.keys() each key (same as above) you want to be extra clear
for v in d.values() each value you only need the values
for k, v in d.items() each key and value together you need both

⚠️ Common Mistakes

A few slips trip people up when they first loop over dictionaries.

  • Expecting values but getting keys. Looping the dictionary directly gives keys, not values. If you wanted the prices, use .values() or .items().

  • Forgetting the two variables with .items(). The method gives a pair, so you need two names to catch them.

prices = {"apple": 30, "banana": 10, "mango": 50}
# ❌ Avoid: one variable can't hold a key-value pair cleanly
for x in prices.items():
print(x) # prints tuples like ('apple', 30)
# βœ… Good: two variables unpack the key and value
for product, price in prices.items():
print(product, price)
  • Using .values() when you need the key too. If you also want to know which product a price belongs to, .values() alone cannot tell you. Reach for .items() instead.
prices = {"apple": 30, "banana": 10, "mango": 50}
# ❌ Avoid: you lose track of which product this price is
for price in prices.values():
print(price)
# βœ… Good: keep the key alongside the value
for product, price in prices.items():
print(product, price)

🌟 Best Practices

Small habits that keep your dictionary loops clean and easy to read.

  • Use .items() when you need both the key and the value. It reads more clearly, and you never repeat the lookup by hand inside the loop.

  • Give your loop variables real names. for product, price reads far better than for k, v. The reader instantly knows what each one holds.

  • Reach for .values() only when the keys truly do not matter, like summing numbers or finding a maximum.

🧩 What You’ve Learned

βœ… Putting a dictionary straight into a for loop gives you its keys, one at a time.

βœ… for product in prices and for product in prices.keys() do exactly the same thing.

βœ… .values() loops over the values and skips the keys, great for sums and totals.

βœ… .items() gives you the key and value together in two variables, the pattern you will use most.

βœ… Pick the method by what you need: keys, values, or both.

Check Your Knowledge

Test what you learned. Pick an answer for each question, then click Check.

  1. 1

    When you loop over a dictionary directly with `for x in my_dict`, what does `x` get on each turn?

    Why: Iterating a dictionary directly gives you its keys, the same as looping over my_dict.keys().

  2. 2

    You want to add up every price in `prices = {'a': 10, 'b': 20}` and you do not need the names. Which is the cleanest choice?

    Why: .values() hands you each value directly, which is perfect when the keys do not matter.

  3. 3

    Which loop gives you the key and the value together on each turn?

    Why: .items() yields each key-value pair, which you unpack into two variables like k and v.

  4. 4

    What happens if you write `for x in prices.items()` with only one loop variable?

    Why: With one variable, x catches the whole pair as a tuple like ('apple', 30) instead of being unpacked.

πŸš€ What’s Next?

You can now read every entry in a dictionary with confidence. Next we turn to what happens when something goes wrong in your code, and how to handle it gracefully.

Introduction to Exceptions

Share & Connect