Counting and iteration

Lesson 40 of 54 · Python Foundations

A frequency dictionary connects each observed value to its number of occurrences. For every item, read its current count or start at zero, then store the incremented count.

visits = ["east", "west", "east", "north"]
counts = {}
for place in visits:
    counts[place] = counts.get(place, 0) + 1
print(counts)
for place, total in counts.items():
    print(place, total)
{'east': 2, 'west': 1, 'north': 1}
east 2
west 1
north 1

The first east starts at zero and becomes one; the second becomes two. Iterating directly over counts gives keys, while counts.items() yields key-value pairs for unpacking. counts.values() provides the values. These are dynamic views of the dictionary; avoid adding or deleting keys while iterating over it.

Since Python 3.7, dictionaries guarantee insertion order. Updating an existing key does not move it; deleting and reinserting it places it at the end. This is not numeric indexing or automatic sorting.

A running comparison can retain both the highest value and its key:

counts = {"east": 2, "west": 2, "north": 1}
best_place = None
best_count = None
for place, total in counts.items():
    if best_count is None or total > best_count:
        best_place, best_count = place, total
print(best_place, best_count)
east 2

Using > rather than >= retains the first key in a tie. With an empty dictionary, both results remain None.