Counter#
collections.Counter is a multiset / frequency map. A
dict subclass where missing keys read as 0 and the type
provides most_common, multiset arithmetic, and bulk update.
from collections import Counter
c = Counter("operator")
c.most_common(3) # [('o', 2), ('p', 1), ('e', 1)]
c["o"] # 2
c["z"] # 0 (no KeyError)
c.update("ranger") # add another iterable
c - Counter("rare") # multiset subtraction
Counter supports +, -, & (min), | (max) over
two counters. Negative counts are allowed during arithmetic
but +counter drops them; -counter drops the positives.
For the top-N use case, prefer c.most_common(N) over
sorted(c.items(), key=lambda kv: -kv[1])[:N]; the former
uses heapq internally and is O(M + N log M) for M unique
elements.
References#
defaultdict for
defaultdict(int), the manual equivalent.Heap for the
heapqthat powersmost_common.