How would you use collections.Counter to efficiently count occurrences and find the most common elements in a large dataset?
Short answer
Counter is a dict subclass specialized for counting hashable items — pass it any iterable to get automatic frequency counts, and use .most_common(n) to efficiently retrieve the top N most frequent elements without writing manual counting logic.
Advertisement
AModel answer
Counter is a dict subclass specialized for counting hashable items — pass it any iterable to get automatic frequency counts, and use .most_common(n) to efficiently retrieve the top N most frequent elements without writing manual counting logic.
from collections import Counter
words = "the quick brown fox jumps over the lazy dog the fox runs".split()
counts = Counter(words)
print(counts["the"]) # 3
print(counts.most_common(2)) # [('the', 3), ('fox', 2)]Real-world example
Analyzing word frequency in a large text corpus, or finding the most common error codes in a log file.
Likely follow-ups
- How does Counter support arithmetic operations like addition and subtraction between two Counter objects?
Related topics