Niras
Niras

Reputation: 455

Sum multiple values for same key in lists using python

I have a list which looks like this:

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

And I want a result that looks like this:

151259627 56
151262958 448
151258350 2576

And here's my code:

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

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

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

If this question has already been asked, please point me there as I was unsuccessful in finding it myself.

Upvotes: 7

Views: 14028

Answers (5)

Animesh Sharma
Animesh Sharma

Reputation: 3386

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)

Upvotes: 3

Delgan
Delgan

Reputation: 19617

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

Upvotes: 1

Ja8zyjits
Ja8zyjits

Reputation: 1503

You can use Counter counters

from collections import Counter

cnt=Counter()
for key,value in l:
    cnt[key] += value

print cnt

part 2

if you found "Animesh's" answer interesting, you can try it in a simpler way: this will not need any imports. 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

Upvotes: 3

J0HN
J0HN

Reputation: 26921

The simplest approach would be 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 descirbed it in the question), replace for key, value in source: with for key, value in source.iteritems():

Upvotes: 2

poke
poke

Reputation: 387547

Use a 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})

Upvotes: 13

Related Questions