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.
Python3
fromcollectionsimportCounter# Create a listz=['blue','red','blue','yellow','blue','red']col_count=Counter(z)print(col_count)col=['blue','red','yellow','green']# Here green is not in col_count # so count of green will be zeroforcolorincol: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.
Python3
# Python example to demonstrate elements()fromcollectionsimportCountercoun=Counter(a=1,b=2,c=3)print(coun)print(list(coun.elements()))
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.
Python3
fromcollectionsimportCountercoun=Counter(a=1,b=2,c=3,d=120,e=1,f=219)# This prints 3 most frequent charactersforletter,countincoun.most_common(3):print('%s: %d'%(letter,count))
We use cookies to ensure you have the best browsing experience on our website. By using our site, you
acknowledge that you have read and understood our
Cookie Policy &
Privacy Policy
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.