Summation of dictionary elements, 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) 

output required:

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

Above is the code I tried, but it gives an error

zip # 1 argument must support iteration

+6
source share
3 answers

The following steps will work on Python 2 or 3:

 >>> {k: [a + b for a, b in zip(*v)] for k, v in d.items()} {'a': [2, 4, 6], 'b': [3, 10, 2]} 

The problem with your code is that you map add_element to every single element in v within your understanding of the dictionary. This passes the one-dimensional zip list to add_element , which leads to an error (as single integers do not support iteration.

+4
source
 >>> 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]} 
+7
source

To fix the source code, you need to do the following:

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

->

 return {k: add_element(v) for k, v in dicty.items()} 

Because zip(*lst) tries to wrap multiple rows in columns, but you only pass one row through your original map

+4
source

All Articles