01 / 20
3 5 2

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.

Python

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.

Input
A sequence of items: ["a","b","a","c","b","a"]
Output
A mapping of each item to its count: {"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.

Input List "a" "b" "a" "c" "b" "a" Dictionary (freq) "a" 3 "b" 2 "c" 1

Where You'll Use This

Text Analysis
Count word or character frequencies in documents, essays, or chat logs.
Data Science
Find the distribution of categories in a dataset: most common value, outliers.
Coding Interviews
Frequency counting appears in anagram checks, "top K" problems, and histogram questions.

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:

Python
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:

Python
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.

Python
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

Strings too
Counter("hello") gives {'l':2, 'h':1, 'e':1, 'o':1}
Arithmetic
c1 + c2 adds counts; c1 - c2 subtracts them.
Missing keys
freq["z"] returns 0 instead of raising a KeyError.

Step-by-Step Approach

1
Identify the data source. What iterable are you counting? A list, string, file lines?
2
Choose your tool. For quick scripts, use .get(). For production code, use Counter.
3
Build the frequency map. Pass the iterable to Counter() or loop with .get(key, 0).
4
Query the results. Access freq[key], call .most_common(n), or iterate over .items().
5
Handle edge cases. Empty input returns {}. Missing keys: Counter gives 0, plain dict raises KeyError.

Example 1: Character Frequency

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

Python
word = "banana"
freq = {}
for ch in word:
    freq[ch] = freq.get(ch, 0) + 1

print(freq)
# {'b': 1, 'a': 3, 'n': 2}
Step-by-step trace: "b" 1 "a" 3 "n" 2 Visual b a n

Example 2: Word Frequency

Find the most common word in a sentence using Counter:

Python
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:

Python
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
"listen" e:1 i:1 l:1 n:1 s:1 t:1 "silent" e:1 i:1 l:1 n:1 s:1 t:1 == True

Example 4: Top K Elements

Given a list of scores, find the two most frequent scores:

Python
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

✕ KeyError on first access
Using freq[item] += 1 without initializing the key first. Use .get(item, 0) or Counter instead.
✕ Forgetting the import
Writing Counter(data) without from collections import Counter at the top of the file.
✕ Counting the wrong thing
Passing a string to Counter when you meant to count words. 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?

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?

Question 5 of 5

What happens when you access a missing key on a Counter object, like c["z"] where "z" was never counted?