← Intro to programming with Python

Looping over dictionaries and counting

Visit every pair, and tally things up.

Start this lesson

To visit every pair in a dictionary, loop over .items(), which hands you the key and the value together: for name, score in scores.items():. Dictionaries are also the perfect tally sheet. To count how often each thing appears, start with an empty dictionary and, for each thing, add 1 to its count, starting it at 0 the first time you see it. This counting pattern is one of the most useful in all of programming.

scores = {"Ana": 12, "Ben": 9}
for name, score in scores.items():
    print(f"{name}: {score}")

votes = ["pizza", "tacos", "pizza", "sushi", "pizza"]
counts = {}
for v in votes:
    counts[v] = counts.get(v, 0) + 1
print(counts)    # {'pizza': 3, 'tacos': 1, 'sushi': 1}

counts.get(v, 0) gives the count so far, or 0 if this is the first time. Then 1 is added and stored back.

Common mistake: counts[v] += 1 on a key that is not there yet gives a KeyError. Use get(v, 0) + 1, or check with in first.

for key in my_dict: on its own loops over the keys only. Use .values() for just the values.