`Counter`
collections.Counter is a dict subclass that counts hashable items. It is a bag or multiset: keys are items, values are counts, and missing keys read as zero.
Detailed Explanation
Counter(iterable) walks the iterable and increments a tally per element. Counter("banana") maps each character to how often it appears. You can also pass a mapping of counts or keyword arguments. Counter is a dict, so c["a"] is the count, and assignment sets it.
Missing keys do not raise. c["z"] is 0. That is convenient and means c["z"] += 1 works without setdefault. The key then exists. elements() iterates each key as many times as its count (skipping non-positive counts). most_common(n) returns the n highest pairs; most_common() returns all, sorted by count.
Arithmetic is defined. a + b adds counts. a - b subtracts and drops non-positive results. a & b takes per-key minimums (intersection). a | b takes maximums (union). In-place forms exist. Counts may be zero or negative if you assign them; the arithmetic operations treat those specially and elements() ignores them.
update adds counts from an iterable or mapping. subtract subtracts and will store negatives. total() (3.10+) sums the counts.
Use a Counter for frequency tables, histograms, and "top n" questions. Use defaultdict(int) when you need a dict that happens to start at zero but is not really a bag (for example, a sparse vector you will pass to an API that wants a plain dict of floats). Convert with dict(counter) when you need a regular dict that does raise on missing keys.
Counter is not thread-safe beyond single opcode updates. Do not increment from two threads without a lock.
Code Examples
from collections import Counter
counts = Counter("banana")
print(counts["a"], counts["z"]) # 3 0
print(counts.most_common(2)) # [('a', 3), ('n', 2)]
print(sorted(counts.elements())) # ['a', 'a', 'a', 'b', 'n', 'n']left = Counter(ada=2, linus=1)
right = Counter(ada=1, grace=4)
print(left + right) # Counter({'grace': 4, 'ada': 3, 'linus': 1})
print(left - right) # Counter({'ada': 1, 'linus': 1})
print(left & right) # Counter({'ada': 1})# Top SKUs from a stream of events.
events = ["A-1", "B-2", "A-1", "A-1", "C-3"]
print(Counter(events).most_common(1)) # [('A-1', 3)]Common Gotchas
Missing keys are zero, not missing
`key in counter` is `False` for a never-seen key, but `counter[key]` is `0`. Use `in` when you mean "was observed".
Negative counts are allowed
`subtract` can produce them. `elements()` skips them. Do not assume every value is `>= 0`.
`most_common` is a sort
`most_common()` on a huge counter is O(n log n). Pass `n` when you only need the top few (`heapq` underneath for small n).
`Counter` equality ignores zero counts
`Counter(a=1, b=0) == Counter(a=1)` is `True`.