Brutalized Brutalized - 2 months ago 8
Python Question

Group sum of list elements based on first and second value

I have the following list:

mylist = [('word1', '10', 200), ('word2', '10', 450), ('word1', '136', 300), ('word2', '110', 666)]


I would like to know how to get the output:

[('10', 650), ('136',300), ('110', 666)]


So add positions [1] and [2] to a new list or dict. But if there is a
word1
and a
word2
with the same [1], add [1] together with the sum of both [2] to the new list or dict.

I hope I'm clear enough, otherwise ask away.

Answer

please rename your list list to list_ (or something else) to not overwrite the reference to the list built-in.

alrd_seen={}
for l in list_:
    alrd_seen[l[1]] = alrd_seen.get(l[1], 0) + l[2]
print list(alrd_seen.items())

with defaultdict;

from collections import defaultdict as dd
alrd_seen = dd(0)
for l in list_:
    alrd_seen[l[1]] += l[2]
print list(alrd_seen.items())