11.16. Counter#
from collections import Counter
11.16.1. Logic#
Counter(pass any iterable here)
It will give dictionary of keys(elements) and values(count)
Accessing the count:
Since it returns dict,you can use counter.keys(),counter.values() and counter.items()
or if you want count of specific key,you can do counter()[‘that key’]
11.16.2. Example#
l=[1,2,3,3,4,5,5,5,5,5,5,5,5,5,5]
print(Counter(l).keys())
print(Counter(l).values())
print(Counter(l).items())
dict_keys([1, 2, 3, 4, 5])
dict_values([1, 1, 2, 1, 10])
dict_items([(1, 1), (2, 1), (3, 2), (4, 1), (5, 10)])
11.16.3. Counting in lists#
l=[1,2,3,3,4,5,5,5,5,5,5,5,5,5,5]
Counter(l)
Counter({1: 1, 2: 1, 3: 2, 4: 1, 5: 10})
11.16.4. Counting in String#
s='sahilsahil'
Counter(s)
Counter({'s': 2, 'a': 2, 'h': 2, 'i': 2, 'l': 2})
11.16.5. Counting in dictionary#
d={
'a':10,
'b':20,
'c':40
}
Counter(d)
Counter({'a': 10, 'b': 20, 'c': 40})
11.16.6. Getting count of specific element#
Counter(d)['c']
40
11.16.7. Extra Functions we can use on Counter object#
l=[1,2,2,3,4,4,5,6,6,6,6,6]
print(Counter(l).most_common(1)) # highest occurence(count)
print(Counter(l).most_common(2)) # top 2 based on occurence(count)
[(6, 5)]
[(6, 5), (2, 2)]
11.16.8. More#
Since it gives dict object,we can use all the dict operations and perform conditions and everything
[k for k,v in Counter(l).items() if v==5]
[6]