01 / 20
{ a : 3 b : 5 } #

Counting with
dict/Counter

Learn to count and track frequencies using Python dictionaries and the powerful Counter class from the collections module.

Python

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.

Input list: a b a c b a count Frequency dict: "a" : 3 "b" : 2 "c" : 1

Why Use a dict for Counting?

Key-Value Mapping
Dictionaries naturally map each unique element (key) to its count (value).
\( O(1) \) Lookup
Checking and updating a count is constant-time on average thanks to hash tables.
Flexible Keys
Any hashable type works as a key: strings, numbers, tuples, and more.

The Manual Loop Pattern

The most fundamental approach: iterate through data and build the frequency dictionary yourself.

words = ["cat", "dog", "cat", "bird", "dog", "cat"] freq = {} for w in words: if w in freq: freq[w] += 1 else: freq[w] = 1 print(freq)
{'cat': 3, 'dog': 2, 'bird': 1}

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.

freq = {} for w in words: freq[w] = freq.get(w, 0) + 1
Before: if/else
4 lines, explicit key check, branching logic.
After: .get()
1 line, default value handles missing keys automatically.

Introducing collections.Counter

Counter is a specialized dictionary subclass in the collections module designed specifically for counting hashable objects.

from collections import Counter words = ["cat", "dog", "cat", "bird", "dog", "cat"] freq = Counter(words) print(freq)
Counter({'cat': 3, 'dog': 2, 'bird': 1})

Counter's Key Methods

1
.most_common(n): returns the n most frequent elements as a list of (element, count) tuples, sorted by count descending.
2
.update(iterable): adds counts from another iterable or Counter, merging into the existing counts.
3
.elements(): returns an iterator over elements, each repeated as many times as its count.
4
Missing key returns 0: unlike a plain dict, accessing a missing key gives 0 instead of a KeyError.

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

1
Identify your data source. What iterable do you need to count? A list, string, file contents, etc.
2
Choose your tool. Need built-in methods like .most_common()? Use Counter. Restricted to basic dict? Use .get() pattern.
3
Build the frequency map. Pass the iterable to Counter() or loop with .get(key, 0) + 1.
4
Query the results. Access counts by key, use most_common(n), or iterate over .items() for all pairs.
5
Handle edge cases. Empty input returns an empty dict/Counter. Missing keys return 0 with Counter or need .get() with dict.

Example 1: Counting Characters

Count the frequency of each character in the string "mississippi".

from collections import Counter text = "mississippi" counts = Counter(text) print(counts) print(counts.most_common(2))
Counter({'s': 4, 'i': 4, 'p': 2, 'm': 1}) [('s', 4), ('i', 4)]

Example 2: Finding the Mode

Given a list of exam scores, find the score that appears most often (the mode).

from collections import Counter scores = [85, 92, 85, 78, 92, 85, 100, 78] c = Counter(scores) mode, count = c.most_common(1)[0] print(f"Mode: {mode}, appears {count} times")
Mode: 85, appears 3 times

Example 3: Word Frequency Analysis

Count words in a sentence and display results using the dict loop pattern for comparison.

sentence = "the cat sat on the mat the cat" words = sentence.split() # Manual dict approach freq = {} for w in words: freq[w] = freq.get(w, 0) + 1 # Sort by count descending sorted_freq = sorted(freq.items(), key=lambda x: x[1], reverse=True) print(sorted_freq)
[('the', 3), ('cat', 2), ('sat', 1), ('on', 1), ('mat', 1)]

Counter Arithmetic

Counter objects support addition, subtraction, intersection, and union operators for combining frequency maps.

from collections import Counter a = Counter("aabbc") # {'a':2, 'b':2, 'c':1} b = Counter("abbcd") # {'b':2, 'a':1, 'c':1, 'd':1} print(a + b) # Add counts print(a - b) # Subtract (keeps positive) print(a & b) # Intersection: min counts print(a | b) # Union: max counts
Counter({'a': 3, 'b': 4, 'c': 2, 'd': 1}) Counter({'a': 1}) Counter({'a': 1, 'b': 2, 'c': 1}) Counter({'a': 2, 'b': 2, 'c': 1, 'd': 1})

How Counter Works Internally

STEP 1: Input Iterable ["a", "b", "a", "c", "a"] STEP 2: Iterate & Hash hash("a") → slot 0 hash("b") → slot 1 hash("c") → slot 2 STEP 3: Result Counter {"a": 3, "b": 1, "c": 1} INTERNAL HASH TABLE Slot 0 "a" → 3 0→1→2→3 Slot 1 "b" → 1 0→1 Slot 2 "c" → 1 0→1 Each encounter increments count by 1

Common Mistakes to Avoid

✕ KeyError on missing key
Using freq[key] += 1 without initializing the key first. Use .get(key, 0) or Counter instead.
✕ Forgetting to import
Writing Counter(data) without from collections import Counter at the top of your file.
✕ Counting mutable objects
Lists and dicts are unhashable and cannot be dictionary keys. Convert to tuples first.

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

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?