tags:

views:

404

answers:

5

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

+9  A: 

Single element:

a_list.count(k)

All elements:

counts = dict((k, a_list.count(k)) for k in set(a_list))
John
Is that not fairly inefficient? You're converting the list to a set, iterating over it and calling a count (presumably O(N) for each item in the set.
Dana
You're right it is more than likely O(n^2), although I think its fun in that python sort of way
John
a generator expression instead of the list comprehension is sufficient. also, using a tuple instead of the inner list looks nicer, i think.
hop
+7  A: 

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)
Dana
that's what I Was gonna post!
hasen j
+13  A: 

Use defaultdict

from collections import defaultdict
kvmap= defaultdict(int)
for k in a_list:
    kvmap[k] += 1
S.Lott
Oh man, I hadn't heard of defaultdict before. Excellent!
Dana
The first time I encountered defaultdict was in Peter Norvig's spelling corrector article. In a couple of lines, he pulls in a file of words and converts it to a dictionary of key=word value=count. Way cool.http://www.norvig.com/spell-correct.html
hughdbrown
+3  A: 

Another solution exploits setdefault():

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

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}
runeh
the outer list comprehension is not necessary; a generator expression is enough.
hop
dict((key, len(list(group))) for (key, group) in itertools.groupby(l))
nosklo