collections.Counter
Published Jul 7, 2022
Contribute to Docs
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.
Note: A Counter
will allow negative counts.
Syntax
myCollection = collections.Counter()
A Counter
can also be initialized from an iterable or initialized from another mapping.
Additional Methods
A Counter
supplies the following additional methods beyond those for a standard dictionary:
.elements()
: Returns an iterator for the keys of theCounter
repeating each element as many times as its count. It will ignore items with a count of less than one..most_common(n)
: Returns then
most common key-count pairs, in descending order of their counts. Ifn
is omitted orNone
, the entire contents of theCollection
are returned..subtract(values)
: Wherevalues
is an iterable or mapping. Matching keys have their values subtracted from the elements in theCounter
. Inputs and outputs can be negative or zero..total()
: Returns the sum of all the counts.
Other differences from a standard dictionary:
- A
Counter
does not implement the.fromkeys()
method. - The
.update()
method adds counter values rather than replacing them, making it the opposite of.subtract()
above.
Codebyte Example
The following example creates a Counter
from an iterable (a string) and outputs various characteristics of the Counter
:
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.