Python Forum

Full Version: collections.Counter()
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
The Counter() in the collections module is a dictionary-like object that keeps distinct elements as keys with their counts as the values. We can use the class to get the occurrences of each element in a given iterable.

#import the Counter class from collections module
from collections import Counter

#An iterable with elements to count
data = 'aabbbccccdeefff'

#create the Counter object
c = Counter(data)

print(c)

#get the count of a specific element
print(c['f'])
Output:
Counter({'c': 4, 'b': 3, 'f': 3, 'a': 2, 'e': 2, 'd': 1}) 3