← Back to all snippets
PYTHON

Counting Frequencies of Items with collections.Counter

Easily count the occurrences of hashable objects in an iterable using Python's `collections.Counter`. Get top common items, total counts, and more with this specialized dict subclass.

from collections import Counter

# Count occurrences of words in a sentence
sentence = "the quick brown fox jumps over the lazy dog quick quick fox"
words = sentence.split()
word_counts = Counter(words)
print(f"Word counts: {word_counts}")

# Access counts
print(f"Count of 'quick': {word_counts['quick']}")
print(f"Count of 'cat' (non-existent): {word_counts['cat']}") # Returns 0 for missing items

# Get the most common words
most_common_words = word_counts.most_common(2)
print(f"2 most common words: {most_common_words}")

# Count characters in a string
char_counts = Counter("hello world")
print(f"Character counts: {char_counts}")

# Performing arithmetic on counters
c1 = Counter('aabbc')
c2 = Counter('abccc')
print(f"c1: {c1}, c2: {c2}")
print(f"c1 + c2 (sum): {c1 + c2}")
print(f"c1 - c2 (difference): {c1 - c2}") # Elements with count <= 0 are removed
How it works: `collections.Counter` is a dictionary subclass designed for counting hashable objects. It's an incredibly convenient tool for tasks like frequency analysis. You can initialize it with an iterable, and it automatically counts the occurrences of each element. It provides useful methods like `most_common()` to retrieve the elements with the highest frequencies, and supports arithmetic operations for combining or comparing counts from different counters.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs