Python dictionaries and frequency counting
Count repeated values using key-value lookup.
On this page
Loops and strings.
- Count repeated values using key-value lookup.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
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) == 0blue 1 red 2
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
counts = {}for word in "red blue red".split(): counts[word] = counts.get(word, 0) + 1for word in sorted(counts): print(word, counts[word])assert counts.get("green", 0) == 0Follow 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
| Step / line | What happens | State after step | Output 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 |
Behind the scenes
How Python processes this code
Python runs this source through its interpreter. It creates objects for values and resolves names as each statement runs.
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.