Home > Software engineering >  Is there a pythonic way of counting the occurrences of each element in an array?
Is there a pythonic way of counting the occurrences of each element in an array?

Time:05-28

Just like the title suggests, I just wanted to know whether there is a pythonic way of counting the occurrence of each element in an array. I have implemented the code below:

my_array = ['dog', 'cat', 'rabbit', 'rabbit', 'elephant', 'bee', 'dog', 'cat', 'cat', 'elephant']

occurrences = {}
for item in my_array:
    try:
        occurrences[item]  = 1
    except KeyError:
        occurrences[item] = 1

And it gives me the ff result:

dog: 2
cat: 3
rabbit: 2
elephant: 2
bee: 1

Is there a more pythonic way of doing this?

PS: Sorry if this question is kind of stupid. I might delete this if someone agrees.

PPS: If this question is duplicated, can u drop the link and I'll give it a go. :)

CodePudding user response:

Counter from the collections module in the standard library is what you are looking for. https://docs.python.org/3/library/collections.html#collections.Counter

Used like so:

from collections import Counter

my_array = ['dog', 'cat', 'rabbit', 'rabbit', 'elephant', 'bee', 'dog', 'cat', 'cat', 'elephant']
c = Counter(my_array)

C then returns Counter({'cat': 3, 'dog': 2, 'rabbit': 2, 'elephant': 2, 'bee': 1})

You can also convert this to a dictionary of elements: counts. dict(c)

  • Related