runtime
38 / 250
lesson 38 Dictionaries & Sets · beginner

Walk the pairs

for key in d visits the keys, and for key, value in d.items() visits the pairs, in the order they were added. You can read values in the loop, but not add or remove keys.

You'll be able to
  • Loop over keys, over items() pairs, and over values()
  • Find the key with the smallest or largest value
  • Explain why adding or removing keys inside the loop raises RuntimeError
The idea

Questions about a whole dictionary need a loop: *which product is cheapest?*, *what is all the stock worth?* for key in d visits each key, in the order the keys were added. d.items() gives each pair, which you unpack into two names: for title, rating in averages.items(). d.values() gives only the values, and d.keys() only the keys.

Run each example to see what it prints. Running examples doesn't count toward progress.

example-1.py · Average rating per film
averages = {"Wild Archive": 3.4, "Night Harbor": 4.6, "Up": 2.8}
for title in averages:
    print(title)
for title, rating in averages.items():
    print(f"{title:<14}{rating:>4}")
print(list(averages.values()))

Searching and totalling follow the same patterns you used on lists, now with a key for every value. To find the cheapest product, remember the best key so far, so you can still report both the ID and its price. To value the stock, walk one dictionary and look up the matching price in another, using the same keys.

example-2.py · Cheapest product and stock value
prices = {"P0035": 47.99, "P0087": 29.99, "P0146": 15.99, "P0164": 31.0}
stock = {"P0035": 4, "P0087": 10, "P0146": 0, "P0164": 2}
cheapest = None
for product_id, price in prices.items():
    if cheapest is None or price < prices[cheapest]:
        cheapest = product_id
value = 0
for product_id, quantity in stock.items():
    value = value + quantity * prices[product_id]
print(cheapest, prices[cheapest])
print(f"stock value {value:.2f}")
example-3.py · Changing the keys while looping
stock = {"P0035": 4, "P0146": 0, "P0164": 2}
for product_id, quantity in stock.items():
    if quantity == 0:
        del stock[product_id]
print(stock)

When to use it: for reports, searches and totals over every pair. Mistakes to avoid:

  • Looping over the dictionary and expecting values. You get keys.
  • Forgetting .items() when you unpack two names, which raises ValueError.
  • Adding or deleting keys inside the loop.
Review
  • for key in d gives keys, d.items() gives (key, value) pairs, and d.values() gives values, all in insertion order.
  • To find the best pair, remember the best key so far, starting from None.
  • Change values in a loop if you need to, but never add or remove keys while looping.
  • Next: sets, for distinct values and for comparing two groups.
Practise this

Loading your progress…

To master this lesson, solve both challenges without hints or the answer, and pass the concept check.

Walk the pairs — Dictionaries & Sets · Runtime