Python 3D Academyবাংলা

Looping over a dictionary

🌍 In real life. At the end of the month, a shop owner goes through the stock book line by line: each item's name and how many are left. They might add up all the counts, or look for the item with the most left over.

Looping over a dictionary means visiting each locker, key by key.

The idea in one sentence: for key in d: visits every key in the order they were added, and d.items() hands you each key with its value.

Its words:

  • for key in d:: loops over the keys
  • d.items(): the (key, value) pairs, ready to unpack: for name, age in d.items():
  • d.values(), d.keys(): just the values, or just the keys
  • best so far: a variable that remembers the winner while you loop

Step by step, for for name in ages::

  1. name gets "Ana", the first key added; ages[name] is 9.
  2. Then "Bo", then "Cy".
  3. Every key has been visited once, so the loop ends.
ages = {"Ana": 9, "Bo": 11, "Cy": 7}
for name in ages:
    print(name, ages[name])

d.items() gives the pairs, so you can unpack each one right in the for line: for key, value in d.items():. d.values() gives just the values, which sum() and max() can use.

ages = {"Ana": 9, "Bo": 11, "Cy": 7}
for name, age in ages.items():
    print(f"{name} is {age}")
print(sum(ages.values()))
print(max(ages.values()))

To find which key has the biggest value, keep the best one so far as you loop:

ages = {"Ana": 9, "Bo": 11, "Cy": 7}
oldest = ""
most = 0
for name, age in ages.items():
    if age > most:
        most = age
        oldest = name
print(oldest, "is the oldest")

What it costs. A loop over a dictionary does one lap per key, and sum(d.values()) and max(d.values()) also walk every value once. .items(), .keys() and .values() don't copy anything; they are live views of the dictionary.

Mistakes and edge cases.

  • Unpacking without items(). for k, v in d: tries to unpack each key; for "Ana" that gives ValueError: too many values to unpack (expected 2).
  • The wrong starting best. Starting most = 0 fails when every value is negative: nothing beats 0. Start with the first value instead (see the bug question).
  • Indexing a view. d.values()[0] gives TypeError: 'dict_values' object is not subscriptable. Write list(d.values())[0].
  • Ties. With >, the first key with the top value wins; with >=, the last one does.

Quiz

  1. What does this print?

    d = {"a": 1, "b": 2}
    for k in d:
        print(k)
  2. What does this print?

    for k, v in {"x": 1, "y": 2}.items():
        print(k * v)
  3. What does this print?

    print(sum({"a": 3, "b": 4}.values()))
  4. What does for k in d: loop over?

    • The keys
    • The values
    • The pairs
  5. What does this print?

    d = {"a": 5, "b": 9, "c": 2}
    best = ""
    most = 0
    for k, v in d.items():
        if v > most:
            most = v
            best = k
    print(best)
  6. Both days were below zero, and Tue was warmer, but this prints an empty line. Which line causes the bug?

    temps = {"Mon": -3, "Tue": -1}
    warmest = ""
    most = 0
    for day, t in temps.items():
        if t > most:
            most = t
            warmest = day
    print(warmest)

Coding tasks

  1. Here are some scores: scores = {"Ana": 7, "Bo": 9, "Cy": 4}. Print one line per player, like Ana: 7.

  2. With the same scores = {"Ana": 7, "Bo": 9, "Cy": 4}, print the total of all the scores, then the name of the player with the highest score.

  3. The shop has prices = {"pen": 10, "book": 50, "bag": 120}. Ask for your budget (a whole number) and print every item you can afford (price at most your budget), one per line, in the shop's order.