Code Snippets
/

Counter for Frequency Counting

Counter for Frequency Counting

`collections.Counter` is the dict-of-counts that every other 'count occurrences' implementation tries to be. It supports increment-by-add, most-common-K, and arithmetic between counters. This snippet covers the basic frequency count, the most-common-K shortcut, and the multiset arithmetic that makes Counter the right choice for inventory math and difference reports.

Python
Easy
3 snippets
py-collections
py-standard-library
code-template
hash-table

1,106 views

25

from collections import Counter

words = ['the', 'quick', 'brown', 'fox', 'jumps', 'over', 'the', 'lazy', 'dog']
freq = Counter(words)
print(freq)
# Counter({'the': 2, 'quick': 1, 'brown': 1, 'fox': 1, 'jumps': 1, 'over': 1, 'lazy': 1, 'dog': 1})

print(freq['the'])  # 2
print(freq['cat']) # 0 (missing key returns 0, never raises)

freq.update(['the', 'dog'])
print(freq['the'])  # 3
print(freq['dog'])  # 2

Passing an iterable to Counter produces a dict-like object where each value is the number of times the key appeared. Counter extends dict, so all dict methods work, but missing keys return 0 instead of raising. update(iterable) increments counts (it does not overwrite, unlike a normal dict update). This is the fastest way to compute character histograms, log-line frequencies, or anagram-equality checks: two strings are anagrams iff their Counters are equal.