Start learning free

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

Looping Over a Dictionary in Python

Lesson

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