A Counter is a data type in the
collections module. It is a
dict subclass that stores counts for hashable objects. For each key-value pair, the key is the item being counted, and the value is the count of that object. A
Counter‘s items are accessed just as in a dictionary, except accessing a missing key will return a
0 value rather than an error.
Counter will allow negative counts.
myCollection = collections.Counter()
Counter can also be initialized from an iterable or initialized from another mapping.
Counter supplies the following additional methods beyond those for a standard dictionary:
.elements(): Returns an iterator for the keys of the
Counterrepeating each element as many times as its count. It will ignore items with a count of less than one.
.most_common(n): Returns the
nmost common key-count pairs, in descending order of their counts. If
nis omitted or
None, the entire contents of the
valuesis an iterable or mapping. Matching keys have their values subtracted from the elements in the
Counter. Inputs and outputs can be negative or zero.
.total(): Returns the sum of all the counts.
Other differences from a standard dictionary:
Counterdoes not implement the
.update()method adds counter values rather than replacing them, making it the opposite of
The following example creates a
Counter from an iterable (a string) and outputs various characteristics of the