Simple Ways to Use Python's Counter (from Collections)

Counter, A counting algorithm. Python provide a brilliant way to deal with counting. So first import our counter

from collections import Counter

Now let's consider a example string

s='abmvakdjvabvkasvb'

Done! Now Watch the magic

print Counter(s)

Output:

Counter({'a': 4, 'v': 4, 'b': 3, 'k': 2, 'd': 1, 'j': 1, 'm': 1, 's': 1})

So Counter is class defined in python collections module, which takes input (hashable objects like string, list etc) and return a dictionary where elements (from hashable objects) are stored as dictionary keys and their counts are stored as dictionary values.

Now let's check another use of Counter.

c=Counter('abmvakdjvabvkasvb')
for letter in s:
    print '%s : %d ' %(letter, c[letter])

Output

a : 4 
b : 3 
m : 1 
v : 4 
a : 4 
k : 2 
d : 1 
j : 1 
v : 4 
a : 4 
b : 3 
v : 4 
k : 2 
a : 4 
s : 1 
v : 4 
b : 3

Python also provide a method to print out the most common elements present in the input.Use most_common() to produce a sequence of the n most frequently encountered input values and their respective counts.

c.most_common(3)

Output:

[('a', 4), ('v', 4), ('b', 3)]

Done!

More about Counter can be learned from Official documentation. If there is anything then Corrections and suggestions are welcome in the comments.