Sum multiple values ​​for the same key in lists with python

I have a list that looks like this:

(151258350, 2464) (151258350, 56) (151262958, 56) (151258350, 56) (151262958, 112) (151262958, 112) (151259627, 56) (151262958, 112) (151262958, 56) 

And I want to get a result that looks like this:

 151259627 56 151262958 448 151258350 2576 

And here is my code:

 for key, vals in d.items(): tempList.append((key, reduce(add, vals))) 

here, d is a list with a key-value pair. tempList is a list in which values ​​will be added after summing them by key. and add fuction:

 def add(x, y): return x+y 

If this question has already been asked, please indicate there, because I could not find it myself.

+4
source share
5 answers
 num_list = [(151258350, 2464), (151258350, 56), (151262958, 56), (151258350, 56), (151262958, 112), (151262958, 112), (151259627, 56), (151262958, 112), (151262958,56)] num_dict = {} for t in num_list: if t[0] in num_dict: num_dict[t[0]] = num_dict[t[0]]+t[1] else: num_dict[t[0]] = t[1] for key,value in num_dict.items(): print "%d %d" %(key,value) 
+3
source

Use Counter :

 >>> l = [(151258350, 2464), (151258350, 56), (151262958, 56), (151258350, 56), (151262958, 112), (151262958, 112), (151259627, 56), (151262958, 112), (151262958, 56)] >>> c = Counter() >>> for k, v in l: c[k] += v >>> c Counter({151258350: 2576, 151262958: 448, 151259627: 56}) 
+7
source

You can use counters

 from collections import Counter cnt=Counter() for key,value in l: cnt[key] += value print cnt 

part 2

If you find an interesting Animesh answer, you can try it easier: you won’t need to import it. Without using .get ()

 l = [(151258350, 2464), (151258350, 56), (151262958, 56), (151258350, 56), (151262958, 112), (151262958, 112), (151259627, 56), (151262958, 112), (151262958, 56)] count={} for k,v in l: if k in count: count[k] += v else: count[k]=v print count 
+2
source

The easiest approach is to use defaultdict

 result = defaultdict(int) for key, value in source: result[key] += value # if you really want result as a list of tuples rslt = list(result.items()) 

If your source is actually a dict (not a list of tuples, as you looked at in the question), replace for key, value in source: with for key, value in source.iteritems():

+1
source

Here is a simple one-liner without importing any library:

 r = dict(set((a, sum(y for x, y in t if x == a)) for a, b in t)) 
+1
source

All Articles