Frequency Counting
with Dicts
Learn how to count occurrences of elements using Python dictionaries, and discover the power of collections.Counter for clean, Pythonic frequency analysis.
What Is Frequency Counting?
Frequency counting means tallying how many times each unique element appears in a collection of data: a list, a string, a file, or any iterable.
["a","b","a","c","b","a"]{"a":3,"b":2,"c":1}Why Use Dictionaries?
A Python dictionary maps keys to values. For frequency counting, each unique element becomes a key and its count becomes the value.
Where You'll Use This
The Core Pattern
The fundamental frequency counting pattern in Python uses a for loop and a dictionary. For each item, check if the key exists, then increment:
freq = {} for item in data: if item in freq: freq[item] += 1 else: freq[item] = 1
Cleaner with .get()
Python's dict.get(key, default) returns the current value if the key exists, or a default value (here, 0) if it doesn't. This collapses 4 lines into 1:
freq = {} for item in data: freq[item] = freq.get(item, 0) + 1
Three Approaches Compared
| Feature | if/else | .get() | Counter |
|---|---|---|---|
| Lines of code | 4 lines | 1 line | 1 line (import + call) |
| Readability | Explicit | Compact | Most Pythonic |
| Extra features | None | None | .most_common(), arithmetic |
| Performance | \( O(n) \) | \( O(n) \) | \( O(n) \) (optimized in C) |
| Best for | Learning | Quick scripts | Production code |
Meet collections.Counter
Python's standard library includes a dedicated class for frequency counting. It's a dict subclass, so it works everywhere a dict works, plus bonus methods.
from collections import Counter data = ["a", "b", "a", "c", "b", "a"] freq = Counter(data) print(freq) # Counter({'a': 3, 'b': 2, 'c': 1}) print(freq.most_common(2)) # [('a', 3), ('b', 2)]
Counter Superpowers
Counter("hello") gives {'l':2, 'h':1, 'e':1, 'o':1}c1 + c2 adds counts; c1 - c2 subtracts them.freq["z"] returns 0 instead of raising a KeyError.Step-by-Step Approach
.get(). For production code, use Counter.Counter() or loop with .get(key, 0).freq[key], call .most_common(n), or iterate over .items().{}. Missing keys: Counter gives 0, plain dict raises KeyError.Example 1: Character Frequency
Count the frequency of each character in the string "banana".
word = "banana" freq = {} for ch in word: freq[ch] = freq.get(ch, 0) + 1 print(freq) # {'b': 1, 'a': 3, 'n': 2}
Example 2: Word Frequency
Find the most common word in a sentence using Counter:
from collections import Counter sentence = "the cat sat on the mat the cat" words = sentence.split() freq = Counter(words) print(freq) # Counter({'the': 3, 'cat': 2, 'sat': 1, 'on': 1, 'mat': 1}) print(freq.most_common(1)) # [('the', 3)]
Example 3: Anagram Check
Two words are anagrams if they have identical character frequencies. Counter makes this a one-liner:
from collections import Counter def is_anagram(s1, s2): return Counter(s1) == Counter(s2) print(is_anagram("listen", "silent")) # True print(is_anagram("hello", "world")) # False
Example 4: Top K Elements
Given a list of scores, find the two most frequent scores:
from collections import Counter scores = [90, 85, 90, 70, 85, 90, 70, 85, 100] freq = Counter(scores) top_two = freq.most_common(2) print(top_two) # [(90, 3), (85, 3)]
Common Mistakes
freq[item] += 1 without initializing the key first. Use .get(item, 0) or Counter instead.Counter(data) without from collections import Counter at the top of the file.Counter("hello world") counts characters, not words.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
What is the output of the following code?
from collections import Counter
c = Counter("mississippi")
print(c["s"])
Question 3 of 5
Which line correctly initializes and increments a frequency dict without using Counter or .get()?
Question 4 of 5
What does Counter("hello world".split()).most_common(1) return?
"hello world".split() produces ["hello", "world"]. Each word appears once. .most_common(1) returns the top 1 item as a list of tuples: [('hello', 1)]. It returns "hello" first because it appeared first.Question 5 of 5
What happens when you access a missing key on a Counter object, like c["z"] where "z" was never counted?