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