collecess.counter (String) .most_common
# getting count
counter = Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})
countDog = counter['Dog']
print(countDog) # 2
Fantastic Frog
# getting count
counter = Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})
countDog = counter['Dog']
print(countDog) # 2
counter = Counter({'Dog': 2, 'Cat': 1, 'Horse': 1})
# setting count
counter['Horse'] = 0
print(counter) # Counter({'Dog': 2, 'Cat': 1, 'Horse': 0})
# setting count for non-existing key, adds to Counter
counter['Unicorn'] = 1
print(counter) # Counter({'Dog': 2, 'Cat': 1, 'Unicorn': 1, 'Horse': 0})
counter = Counter({'Dog': 2, 'Cat': -1, 'Horse': 0})
# elements()
elements = counter.elements() # doesn't return elements with count 0 or less
for value in elements:
print(value)
# Counter works with non-numbers too
special_counter = Counter(name='Pankaj', age=20)
print(special_counter) # Counter({'name': 'Pankaj', 'age': 20})
# getting count for non existing key, don't cause KeyError
print(counter['Unicorn']) # 0
# Delete element from Counter
del counter['Unicorn']
print(counter) # Counter({'Dog': 2, 'Cat': 1, 'Horse': 0})