Python’s Collections Module: Counter

Introduction

A Counter is a dict subclass for counting hashable objects → any object which is not mutable.

It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values.

#To use it, ofc…


This content originally appeared on DEV Community and was authored by Kathan Vakharia

Introduction

A Counter is a dict subclass for counting hashable objects → any object which is not mutable.

It is a collection where elements are stored as dictionary keys and their counts are stored as dictionary values.

#To use it, ofcourse we need to first import it
from collections import Counter

Using Counter

myList = ['k', 'k', 1, 1, 2, 2, 1, 2, 3, 3, 1, 'a']
myString = "CodeBlooded"

# simply pass any iterable
# Counter(iterable) returns a Counter obj
count1 = Counter(myList)
count2 = Counter(myString)

#How does a Counter obj look?
print(count1, count2, sep='\n')

"""Output
Counter({1: 4, 2: 3, 'k': 2, 3: 2, 'a': 1})
Counter({'o': 3, 'd': 3, 'e': 2, 'C': 1, 'B': 1, 'l': 1})
""""

? As counter is a subclass of dictionary, it has all the methods of the dictionary.

most_common(n) method

The most_common(n) returns a list of n most common objects along with their respective counts.

from collections import Counter

myList = ['k', 'k', 1, 1, 2, 2, 1, 2, 3, 3, 1, 'a']
myString = "CodeBlooded"

# simply pass any iterable
# Counter(iterable) returns a Counter object
count1 = Counter(myList)
count2 = Counter(myString)


print(count1, count2, sep='\n')

# If n is omitted or None, most_common()
# returns all elements in the counter.
print(count1.most_common(2))
print(count2.most_common(3))

"""Output
Counter({1: 4, 2: 3, 'k': 2, 3: 2, 'a': 1})
Counter({'o': 3, 'd': 3, 'e': 2, 'C': 1, 'B': 1, 'l': 1})
[(1, 4), (2, 3)]
[('o', 3), ('d', 3), ('e', 2)]
"""

Common Patterns with Counter

For a given Counter object c,
image

? Feel free to fire up your ipython or python shell and try this commands out for better understanding :)

Let's wrap up this post with a problem where Counter is very helpful.

Finding most frequent word using Counter in a given string

from collections import Counter

string = "string with repeated word Jello So what is Jello Who cares what is Jello anyways but Jello must be repeated Jello number of Jello times"

# You can use re.split() for more complex patterns!
words = string.split()
words_count = Counter(words)
print("Most Occurring word is",
      words_count.most_common(1))

"""Output
Most Occurring word is [('Jello', 6)]
"""

❓ if you notice, while printing the Counter object - it doesn't maintain the order of elements present in the iterable passed. Do you know why?

Try googling or duckduckgoing! I will answer this question in next post ?


This content originally appeared on DEV Community and was authored by Kathan Vakharia


Print Share Comment Cite Upload Translate Updates
APA

Kathan Vakharia | Sciencx (2021-06-13T06:40:22+00:00) Python’s Collections Module: Counter. Retrieved from https://www.scien.cx/2021/06/13/pythons-collections-module-counter/

MLA
" » Python’s Collections Module: Counter." Kathan Vakharia | Sciencx - Sunday June 13, 2021, https://www.scien.cx/2021/06/13/pythons-collections-module-counter/
HARVARD
Kathan Vakharia | Sciencx Sunday June 13, 2021 » Python’s Collections Module: Counter., viewed ,<https://www.scien.cx/2021/06/13/pythons-collections-module-counter/>
VANCOUVER
Kathan Vakharia | Sciencx - » Python’s Collections Module: Counter. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2021/06/13/pythons-collections-module-counter/
CHICAGO
" » Python’s Collections Module: Counter." Kathan Vakharia | Sciencx - Accessed . https://www.scien.cx/2021/06/13/pythons-collections-module-counter/
IEEE
" » Python’s Collections Module: Counter." Kathan Vakharia | Sciencx [Online]. Available: https://www.scien.cx/2021/06/13/pythons-collections-module-counter/. [Accessed: ]
rf:citation
» Python’s Collections Module: Counter | Kathan Vakharia | Sciencx | https://www.scien.cx/2021/06/13/pythons-collections-module-counter/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.