Home > Mobile >  Columnwise sum in a dictionary
Columnwise sum in a dictionary

Time:04-25

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?

CodePudding user response:

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 .

CodePudding user response:

Iterate over all the keys k in the dictionary d, and for each k, add the 3-tuple d[k] to the current sum res:

d = {"adi":(1,2,4),"simon":(1,7,0),"lus":(3,1,2)}
res = [0,0,0]
for k in d:
    res = [res[i]   d[k][i] for i in range(3)]
print(tuple(res))
  • Related