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
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
Single element:
a_list.count(k)
All elements:
counts = dict((k, a_list.count(k)) for k in set(a_list))
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)
Use defaultdict
from collections import defaultdict
kvmap= defaultdict(int)
for k in a_list:
kvmap[k] += 1
Another solution exploits setdefault():
for k in a_list:
kvMap[k] = kvMap.setdefault(k, 0) + 1
If your list is sorted, an alternative way would be to use itertools.groupby. This might not be the most effective way, but it's interesting nonetheless. It retuns a dict of item > count :
>>> import itertools
>>> l = [1,1,2,3,4,4,4,5,5,6,6,6,7]
>>> dict([(key, len([e for e in group]))
for (key, group)
in itertools.groupby(l)])
{1: 2, 2: 1, 3: 1, 4: 3, 5: 2, 6: 3, 7: 1}