Skip to content

How to count items with a Python dictionary

October 31, 2026 · 1 min read

To count items with a dictionary, loop over them and update each item's count with counts[item] = counts.get(item, 0) + 1. The .get() method returns 0 the first time you see an item, so you never get a KeyError.

A word-frequency counter

text = "the cat sat on the mat the end"
counts = {}

for word in text.split():
    counts[word] = counts.get(word, 0) + 1

print(counts)

for word, n in counts.items():
    print(f"{word}: {n}")

Output:

{'the': 3, 'cat': 1, 'sat': 1, 'on': 1, 'mat': 1, 'end': 1}
the: 3
cat: 1
sat: 1
on: 1
mat: 1
end: 1

How it works

  • text.split() breaks the string into a list of words.
  • counts starts as an empty dict. Each key is a word and each value is how many times you have seen it.
  • counts.get(word, 0) returns the current count, or 0 if the word is not in the dict yet.
  • Adding 1 and assigning the result back stores the new count. A new word gets added, and an existing word gets replaced with a bigger number.
  • .items() gives you each key and value together, so you can print the results.

The same pattern works for any list: products sold, votes, letters in a string.

Common mistake

Reading the count with square brackets fails on the first sighting of a word:

counts = {}
counts["the"] = counts["the"] + 1   # KeyError: 'the'

The key does not exist yet, so Python stops. Use counts.get("the", 0) instead, which falls back to 0.

A second mistake is forgetting to make the words consistent. "The" and "the" are different keys. Call .lower() on the text first:

for word in text.lower().split():
    counts[word] = counts.get(word, 0) + 1

Takeaway

A dict plus .get(key, 0) is all you need to count anything. Loop, read the count with a default of 0, add 1, and store it back.

More on Python