Open In App
Related Articles

Counters in Python | Set 2 (Accessing Counters)

Like Article
Save Article
Report issue

Counters in Python | Set 1 (Initialization and Updation)

Counters in Python | Set 2

Once initialized, counters are accessed just like dictionaries. Also, it does not raise the KeyValue error (if key is not present) instead the value’s count is shown as 0.

Example: In this example, we are using Counter to print the key and frequency of that key. The elements present inside the frequency map are printed along with their frequency and if the element is not present inside the Counter map then the element will be printed along with 0.


from collections import Counter
# Create a list
z = ['blue', 'red', 'blue', 'yellow', 'blue', 'red']
col_count = Counter(z)
col = ['blue','red','yellow','green']
# Here green is not in col_count 
# so count of green will be zero
for color in col:
    print (color, col_count[color])

Output: <
Counter({‘blue’: 3, ‘red’: 2, ‘yellow’: 1})
blue 3
red 2
yellow 1
green 0

elements() method of Counter in Python

The elements() method returns an iterator that produces all of the items known to the Counter. Note: Elements with count <= 0 are not included.

Example : In this example, the elements inside the Counter would be printed by using the elements() method of Counter.


# Python example to demonstrate elements()
from collections import Counter
coun = Counter(a=1, b=2, c=3)

Output :
Counter({'c': 3, 'b': 2, 'a': 1})
['a', 'b', 'b', 'c', 'c', 'c']

most_common() method of Counter in Python

most_common() is used to produce a sequence of the n most frequently encountered input values and their respective counts. If the parameter ‘n’ is not specified or None is passed as the parameter most_common() returns a list of all elements and their counts.

Example: In this example, the element with the most frequency is printed followed by the next-most frequent element by using most_common() method inside Counter in Python.


from collections import Counter
coun = Counter(a=1, b=2, c=3, d=120, e=1, f=219)
# This prints 3 most frequent characters
for letter, count in coun.most_common(3):
    print('%s: %d' % (letter, count))

Output :
f: 219
d: 120
c: 3

Last Updated : 06 Sep, 2023
Like Article
Save Article
Share your thoughts in the comments
Similar Reads