collections.Counter

A dictionary for counting: for each item, it stores the number of times it occurs.

Returns
A Counter object, that is a dictionary of occurrence counts.
On this page

Example

#
Python
from collections import Counter

answers = ["B", "A", "B", "C", "B", "A"]
counts = Counter(answers)

print(counts)
print(counts["B"], counts["D"])
print(counts.most_common(1))
Resultsaved result, you can check it
Counter({'B': 3, 'A': 2, 'C': 1})
3 0
[('B', 3)]

Definition and usage

#

The Counter class from the collections module counts the items of a collection in one step. Counter(["a", "b", "a"]) creates a dictionary whose keys are the items and whose values are the number of times they occur. It works with lists, strings (it counts characters), and any other collection.

The most_common(n) method returns a list of the n most frequent items together with their counts, sorted from the largest. Reading a missing key returns 0 instead of raising KeyError, so there is nothing to check before incrementing a counter.

Counter is a subclass of dict, so everything you know from dictionaries works on it. In addition, counters can be added and subtracted with the + and - operators, and the update() method adds new occurrences instead of replacing values. The sum of all the counts is returned by total().

Syntax

#
Syntax
from collections import Counter

Counter(iterable)
counter.most_common(n)
counter.update(iterable)
counter.total()

Parameters

#
  • iterable

    collection or dictionary, optional

    The items to count, or a dictionary with ready-made counts.

More examples

#
The most common words in a text
Python
from collections import Counter

text = "python is simple and python is popular"
words = Counter(text.split())

for word, count in words.most_common(2):
    print(word, count)

print(Counter("banan"))
Resultsaved result, you can check it
python 2
is 2
Counter({'a': 2, 'n': 2, 'b': 1})
Adding and updating counters
Python
from collections import Counter

week1 = Counter(html=3, python=1)
week2 = Counter(python=4, css=2)

print(week1 + week2)

week1.update(["html", "css"])
print(week1)
print(week1.total())
Resultsaved result, you can check it
Counter({'python': 5, 'html': 3, 'css': 2})
Counter({'html': 4, 'python': 1, 'css': 1})
6

Good practices

#
  • Reading a missing key returns 0, but does not add it to the counter. That is why counts[x] += 1 works without checking the key first.
  • update() in Counter adds counts, rather than replacing them as in an ordinary dictionary.
  • In a tie, most_common() keeps the order in which the items first appeared.

Related entries

#

Practise it in lessons

#

Spotted a mistake or missing an example? Write to us.