Start learning free

LESSON 222 OF 673 · LOOPS WITH STRINGS, LISTS & DICTIONARIES

Looping Over Dictionaries in Python

Lesson Read the full explanation

TL ; DR:

A for loop over .items() visits every key of a dictionary with its value. A loop over the dictionary itself visits only the keys.


stock = {"apples": 5, "pears": 2}

for fruit, amount in stock.items():
    print(fruit, amount)

# apples 5
# pears 2


Full lesson:

A loop can visit every entry of a dictionary, one at a time. The loop body runs once per key.

.items() hands the loop each key together with its value. The loop has a variable for each. The key comes first, then the value.

Loop over the dictionary itself to get only the keys. You can still read each value with its key.

for fruit in stock:
    print(fruit, stock[fruit])

The order: Python keeps the keys in the order they were added. Many other languages don't. A total or a count comes out the same in any order. Those are safe answers.

Watch out: don't add or delete keys inside the loop. Python stops with a RuntimeError.


Your task

A game keeps each player's points in scores. The variables total and count start at 0.

Loop over scores. Add every player's points to total. Count the players with 10 points or more in count.

The code at the bottom prints both.

Expected output:

43
2
STEP 1 OF 3
    Ctrl + Enter to check

    PYTHON · LOOPS WITH STRINGS, LISTS & DICTIONARIES

    Looping Over Dictionaries in Python, explained

    What a dictionary loop does

    A for loop can visit every entry of a dictionary, one at a time. The loop body runs once per key. There are two ways to write it, and they differ in what the loop variables hold.

    Keys and values together: items()

    scores.items() hands the loop each key with its value. Give the loop two variables: the key comes first, the value second.

    scores = {"Ana": 12, "Ben": 7, "Cleo": 15, "Dan": 9}
    
    for name, points in scores.items():
        print(name, points)
    Ana 12
    Ben 7
    Cleo 15
    Dan 9

    Each turn of the loop receives a pair such as ("Ana", 12), and Python unpacks it into name and points. With a single variable you get the whole pair as a tuple.

    Keys only: the dictionary itself

    A loop over the dictionary gives only the keys. You can still read each value with the key:

    for name in scores:
        print(name, scores[name])

    This prints the same four lines. Use items() when you need both, because it reads more clearly than looking each value up again.

    Other ways to look at a dictionary

    Two more views are handy. scores.keys() gives only the keys and scores.values() gives only the values. For the exercise's dictionary, list(scores.keys()) is ['Ana', 'Ben', 'Cleo', 'Dan'] and list(scores.values()) is [12, 7, 15, 9]. When only the values matter, as in a plain total, for points in scores.values(): is enough. The exercise also needs a count of players, but it needs no names, so that loop could use .values() too.

    Order

    Python keeps the keys in the order they were added, so the loops above print Ana, Ben, Cleo, Dan. Many other languages make no such promise. When the answer is a total or a count, the order cannot change it, so those are safe results to compute in a loop.

    Traps

    • Two variables over the dictionary itself. for a, b in scores: tries to split each key, a string, into two parts, and stops with ValueError: too many values to unpack (expected 2). Add .items().
    • Changing the keys during the loop. Adding or deleting a key inside the loop stops the program with RuntimeError: dictionary changed size during iteration. Collect what you want to change first, and change the dictionary after the loop. Changing the value of an existing key is allowed.
    • Mixing up the order of the variables. for points, name in scores.items() is legal, but points now holds the keys.

    The exercise, step by step

    The dictionary scores maps each player to their points. The task: add up all the points in total, and count in count the players with 10 points or more.

    1. Write for name, points in scores.items(): below the line that sets count to 0.
    2. Inside the loop, add points to total.
    3. Still inside, if points is 10 or more, add 1 to count.
    scores = {"Ana": 12, "Ben": 7, "Cleo": 15, "Dan": 9}
    total = 0
    count = 0
    
    for name, points in scores.items():
        total += points
        if points >= 10:
            count += 1
    
    print(total)
    print(count)

    The output is:

    43
    2

    The total is 12 + 7 + 15 + 9 = 43. Ana (12) and Cleo (15) reach 10, so the count is 2. The variable name is never used here, which is fine: the loop still needs a place to put the key.

    Key takeaways

    • for key, value in d.items(): visits every key with its value.
    • for key in d: visits only the keys; read the value with d[key].
    • Python dictionaries remember insertion order, but totals and counts do not depend on it.
    • Do not add or delete keys while looping.
    Keep going with Python500+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free