python sum tuple list based on tuple first value

list, python, sum

Solution

You can use `collections.defaultdict`:

>>> from collections import defaultdict
>>> from operator import mul
>>> lis = [(0,2),(1,3),(2,4),(0,5),(1,6)]
>>> dic = defaultdict(list)
>>> for k,v in lis:
    dic[k].append(v)  #use the first item of the tuple as key and append second one to it
...     

#now multiply only those lists which contain more than 1 item and finally sum them.
>>> sum(reduce(mul,v) for k,v in dic.items() if len(v)>1)
 28

Problem

Suppose I have the following list tuples: ``` myList = [(0,2),(1,3),(2,4),(0,5),(1,6)] ``` I want to sum this list based on the same first tuple value: ``` [(n,m),(n,k),(m,l),(m,z)] = m*k + l*z ``` For `myList` ``` sum = 2*5 + 3*6 = 28 ``` How can I got this?

Original source