Counter

A Counter is a dict subclass for counting hashable objects. It is an ordered collection, where counts can be zero or negative.

Initialization

from collections import Counter
c = Counter()                           # a new, empty counter
c = Counter('gallahad')                 # a new counter from an iterable
c = Counter({'red': 4, 'blue': 2})      # a new counter from a mapping
c = Counter(cats=4, dogs=8)             # a new counter from keyword args

Methods

words = ['the', 'sheep', 'was', 'a', 'black', 'sheep']
Counter(words).most_common(2) # [('sheep', 2), ('black', 2)]
c = Counter(a=4, b=2, c=0, d=-2)
list(c.elements()) # ['a', 'a', 'a', 'a', 'b', 'b'] negative counts or zero counts are disregarded.
c = Counter(a=3, b=1)
d = Counter(a=1, b=2)
c + d # add two counters together: c[x] + d[x]
Counter({'a': 4, 'b': 3})
c - d # subtract (keeping only positive counts)
Counter({'a': 2})
c & d # intersection:  min(c[x], d[x])
Counter({'a': 1, 'b': 1})
c | d # union:  max(c[x], d[x])
Counter({'a': 3, 'b': 2})
sum(c.values()) # total of all counts
c.clear() # reset all counts
list(c) # list unique elements
set(c) # convert to a set
dict(c) # convert to a regular dictionary
c.items() # convert to a list of (elem, cnt) pairs
Counter(dict(list_of_pairs)) # convert from a list of (elem, cnt) pairs
c.most_common()[:-n-1:-1] # n least common elements
+c # remove zero and negative counts