Skip to content Skip to sidebar Skip to footer

How To Sum Values In Dictionary Based On Position?

I have a dictionary that for each key there are five values in list, such as: {'A': [0, 0.12, 0, 0.73, 0], 'B': [0.96, 0, 0.30, 0, 0], 'C': [0, 0, 0, 0.11, 0], 'D': [0, 0.07,

Solution 1:

You can use the zip() function

aa = {"A": [0, 0.12, 0, 0.73, 0], "B": [0.96, 0, 0.30, 0, 0], "C": [0, 0, 0, 0.11, 0], "D": [0, 0.07, 0, 0.42, 0]}
bb = []

for value in (zip(*list(aa.values()))):
           bb.append(sum(value))


print (bb)  

output :

 [0.96, 0.19, 0.3, 1.26, 0]

Solution 2:

do you mind using numpy? if not you can use this

aa = {"A": [0, 0.12, 0, 0.73, 0], "B": [0.96, 0, 0.30, 0, 0], "C": [0, 0, 0, 0.11, 0],  "D": [0, 0.07, 0, 0.42, 0]}

import numpy as np
bb = np.array([aa.get(a) for a in aa])
print(np.sum(bb, axis=0))

the output will be : [ 0.96 0.19 0.3 1.26 0. ]


Solution 3:

You can use reduce in addition with zip to calculate sum by element wise.

from functools import reduce

a = {"A": [0, 0.12, 0, 0.73, 0], "B": [0.96, 0, 0.30, 0, 0],
  "C": [0, 0, 0, 0.11, 0],    "D": [0, 0.07, 0, 0.42, 0]}

b = reduce(lambda x, y: ([x1 + y1 for x1,y1 in zip(x,y)]), a.values())

Solution 4:

You can try more simple way :

>>> aa = {"A": [0, 0.12, 0, 0.73, 0], "B": [0.96, 0, 0.30, 0, 0], "C": [0, 0, 0, 0.11, 0], "D": [0, 0.07, 0, 0.42, 0]}
>>> b = [sum(value) for value in zip(*aa.values())]
>>> b
[0.96, 0.19, 0.3, 1.26, 0]
>>>

Solution 5:

First of all, you want to use aa.values(), not aa.items(). aa.items gives tuples of (key, value), but you just want the values.

Second of all, you want to sum the items in the list, so use sum.

aa = {"A": [0, 0.12, 0, 0.73, 0], "B": [0.96, 0, 0.30, 0, 0], "C": [0, 0, 0, 0.11, 0], "D": [0, 0.07, 0, 0.42, 0]}
bb = []
for value in (aa.values()):
        bb.append(sum(value))

Post a Comment for "How To Sum Values In Dictionary Based On Position?"