Mar-29-2024, 05:52 PM
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