Python dictionaries and frequency counting

Count repeated values using key-value lookup.

Python
counts = {}
for word in "red blue red".split():
    counts[word] = counts.get(word, 0) + 1
for word in sorted(counts):
    print(word, counts[word])
assert counts.get("green", 0) == 0
Output
blue 1
red 2

Explanation

A dictionary maps each distinct key to a value. get(key, 0) supplies zero when a word has not appeared yet, then the count is incremented.

The sample sorts keys for predictable display. The counting itself does not require sorted words. Splitting on whitespace is a simple tokenization rule, not a full natural-language parser.

Explore the dry run
Guided walkthroughReady
1counts = {}
2for word in "red blue red".split():
3 counts[word] = counts.get(word, 0) + 1
4for word in sorted(counts):
5 print(word, counts[word])
6assert counts.get("green", 0) == 0

Follow the example

Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.

View the complete dry-run table
Prepared trace of the published program. Some rows group repeated iterations.
Step / lineWhat happensState after stepOutput so far
Start an empty dictionary.counts = {}
—
First token red starts at zero and becomes one.counts = {'red': 1}
—
Token blue creates a second entry.counts = {'red': 1, 'blue': 1}
—
The next red increments its existing count.counts = {'red': 2, 'blue': 1}
—
Sort keys for deterministic output.keys = ['blue', 'red']
—
Print both entries in that order.keys = ['blue', 'red']
blue 1
red 2

Cost and common mistakes

Expected O(n) counting for n bounded-size tokens; sorting k distinct keys adds O(k log k). O(k) dictionary space. Hash collisions can worsen lookup performance.

  • Dictionary keys must be hashable.
  • red and Red are distinct unless you normalize case before counting.

Try it yourself

Count 'red red blue green'.

Reveal answer and reasoning

Sorted output is blue 1, green 1, red 2 on separate lines.

Further reading