I want to sum all the values by their places.
For example, given:
dict= {"adi":(1,2,4),"simon":(1,7,0),"lus":(3,1,2)}
I want to perform the following operation:
(1+1+3,2+7+1,4+0+2)----> (5,10,6)
How can I accomplish this?
We can zip(*data.values())
to transpose the values in the dictionary, and then we can use sum()
and a list comprehension to get our final result:
[sum(val) for val in zip(*data.values())]
This outputs:
[5, 10, 6]
Note that I'm using data
rather than dict
as a variable name, as the latter is the name of a built-in. Note also that this relies on the fact that dictionaries preserve insertion order, which is only true on Python 3.7+.