2

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. :)

Seven
  • 330
  • 2
  • 15
  • 1
    Does this answer your question? [How do I count the occurrences of a list item?](https://stackoverflow.com/questions/2600191/how-do-i-count-the-occurrences-of-a-list-item) – Joooeey May 28 '22 at 11:08
  • 1
    There is the `Counter` class from collections. – quamrana May 28 '22 at 11:09
  • @Joooeey not really. it only counts a given item in a list. My problem is more like counting the occurrence of each element and I have solved it. Just wondering if there's a pythonic way of doing so. – Seven May 28 '22 at 11:10
  • @Hansel, the second answer to the linked question answers your question pythonically: https://stackoverflow.com/a/5829377/4691830 – Joooeey May 28 '22 at 11:11

1 Answers1

1

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)

ross-g
  • 105
  • 6