collections. Counter
A dictionary for counting: for each item, it stores the number of times it occurs.
- Returns
- A
Counterobject, that is a dictionary of occurrence counts.
Example
#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))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
#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
#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"))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())Good practices
#- Reading a missing key returns 0, but does not add it to the counter. That is why
counts[x] += 1works without checking the key first. update()inCounteradds 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
#- collections.defaultdictA dictionary that creates a default value on its own for a missing key, e.g. an empty list or zero.
- str.count()Counts non-overlapping occurrences of a fragment in a string.
- list.count()Counts how many times a value occurs in a list.
- dict.get()Returns the value for a key, or a default value when the key is not in the dictionary.
- max()Returns the largest item in a collection, or the largest of several arguments.
- collections.dequeA double-ended queue: fast adding and removing of items at both ends, optionally with a length limit.
Practise it in lessons
#Spotted a mistake or missing an example? Write to us.