# Python Day -07 - Counter
# useful dict subclass for counting it's elements
# element can be a string, dictionary, or keyword args
from collections import Counter
string_counter = Counter('aasddhhssdhdhdd')
print(string_counter)
# Prints Counter({'d': 6, 'h': 4, 's': 3, 'a': 2})
print(string_counter.most_common(2))
# Prints [('d', 6), ('h', 4)], the most common elements
# with element and element count tuple
print(list(string_counter.elements()))
# Prints ['a', 'a', 's', 's', 's', 'd', 'd', 'd', 'd', 'd', 'd', 'h', 'h', 'h', 'h']
# all the elements
print(string_counter['d'])
# Prints 6, count of element d
print(string_counter['w'])
# Prints 0 as there is no element w
![Cover image for Beginner Python tips Day - 07 Counter](https://media.dev.to/cdn-cgi/image/width=1000,height=420,fit=cover,gravity=auto,format=auto/https%3A%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fi%2F05h18b4szeg89a12g6yy.png)
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (0)