Counting with
dict/Counter
Learn to count and track frequencies using Python dictionaries and the powerful Counter class from the collections module.
What Is Frequency Counting?
Frequency counting means tallying how many times each unique element appears in a collection. Given a list like ["a", "b", "a", "c", "b", "a"], the goal is to produce a mapping: "a" appears 3 times, "b" appears 2 times, "c" appears 1 time.
Why Use a dict for Counting?
The Manual Loop Pattern
The most fundamental approach: iterate through data and build the frequency dictionary yourself.
Cleaner Code with .get()
The if/else check can be replaced by dict.get(key, default), which returns a default value when the key is missing.
Introducing collections.Counter
Counter is a specialized dictionary subclass in the collections module designed specifically for counting hashable objects.
Counter's Key Methods
dict vs Counter
| Plain dict | Counter | |
|---|---|---|
| Import needed | No | Yes (collections) |
| Counting code | Manual loop | One-liner |
| Missing key | KeyError | Returns 0 |
| most_common() | Manual sort | Built-in |
| Arithmetic | Manual | +, -, &, | operators |
| Best for | Learning, simple cases | Production code |
How to Apply: Step by Step
Example 1: Counting Characters
Count the frequency of each character in the string "mississippi".
Example 2: Finding the Mode
Given a list of exam scores, find the score that appears most often (the mode).
Example 3: Word Frequency Analysis
Count words in a sentence and display results using the dict loop pattern for comparison.
Counter Arithmetic
Counter objects support addition, subtraction, intersection, and union operators for combining frequency maps.
How Counter Works Internally
Common Mistakes to Avoid
Question 1 of 5
What does freq.get("x", 0) return if "x" is not a key in the dictionary freq?
Question 2 of 5
Given c = Counter("banana"), what does c.most_common(1) return?
Question 3 of 5
What happens when you access Counter(["a", "b"])["z"]?
Question 4 of 5
Consider this code:
freq = {}
data = [1, 2, 2, 3, 3, 3]
for x in data:
freq[x] = freq[x] + 1
print(freq)
What will happen when this code runs?
Question 5 of 5
Which of the following correctly counts how many times each word appears in a list called words?