Skip to content Skip to sidebar Skip to footer

What's The Pythonic Way To Count The Occurrence Of An Element In A List?

this is what I did. is there a better way in python? for k in a_list: if kvMap.has_key(k): kvMap[k]=kvMap[k]+1 else: kvMap[k]=1 Thanks

Solution 1:

Use defaultdict

from collections import defaultdict
kvmap= defaultdict(int)
for k in a_list:
    kvmap[k] += 1

Solution 2:

Single element:

a_list.count(k)

All elements:

counts = dict((k, a_list.count(k)) for k in set(a_list))

Solution 3:

I dunno, it basically looks fine to me. Your code is simple and easy to read which is an important part of what I consider pythonic.

You could trim it up a bit like so:

for k in a_list:
     kvMap[k] = 1 + kvMap.get(k,0)

Solution 4:

Such an old question, but considering that adding to a defaultdict(int) is such a common use, It should come as no surprise that collections has a special name for that (since Python 2.7)

>>> from collections import Counter
>>> Counter([1, 2, 1, 1, 3, 2, 3, 4])
Counter({1: 3, 2: 2, 3: 2, 4: 1})
>>> Counter("banana")
Counter({'a': 3, 'n': 2, 'b': 1})

Solution 5:

Another solution exploits setdefault():

for k in a_list:
    kvMap[k] = kvMap.setdefault(k, 0) + 1

Post a Comment for "What's The Pythonic Way To Count The Occurrence Of An Element In A List?"