Beginner Python tips Day - 07 Counter
Paurakh Sharma Humagain
Posted on June 10, 2020
# 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
💖 💪 🙅 🚩
Paurakh Sharma Humagain
Posted on June 10, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.