Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Summation of elements of dictionary that are list of lists

d = {
  'a': [[1, 2, 3], [1, 2, 3]],
  'b': [[2, 4, 1], [1, 6, 1]],
}

def add_element(lst):
    ad = [sum(i) for i in zip(*lst)]
    return ad

def csv_reducer2(dicty):
    return {k: list(map(add_element, v)) for k, v in dicty.items()}

csv_reducer2(d)

required output:

{'b': [3, 10, 2], 'a': [2, 4, 6]}

Above is the code I have been trying but it gives an error

zip argument #1 must support iteration

like image 918
Iqbal Avatar asked Oct 12 '16 23:10

Iqbal


1 Answers

>>> d = {'a': [[1, 2, 3], [1, 2, 3]], 'b': [[2, 4, 1], [1, 6, 1]]}
>>> {k: map(sum, zip(*v)) for k, v in d.items()}
{'a': [2, 4, 6], 'b': [3, 10, 2]}
like image 54
Transhuman Avatar answered Nov 15 '22 09:11

Transhuman