Home > Mobile >  Sum Values in List of Dictionaries with some elements as list
Sum Values in List of Dictionaries with some elements as list

Time:11-16

I have this list of dictionaries:


list_of_dicts = [{'A':1,'B':2,'C':3,'D':4,'E':5}, {'A':1,'B':1,'C':1,'D':1,'E':1}, {'A':2,'B':2,'C':2,'D':2,'E':2}]

To sum up values, I can use counter like this:

from collections import Counter
import functools, operator
# sum the values with same keys
counter = Counter()
for d in list_of_dicts: 
    counter.update(d)
      
result = dict(counter) 
result
{'A': 4, 'B': 5, 'C': 6, 'D': 7, 'E': 8}

But how to achieve summation if some key in the dictionary has value as list:

list_of_dicts = [{'A':1,'B':2,'C':3,'D':4,'E':[1,2,3]}, {'A':1,'B':1,'C':1,'D':1,'E':[1,2,3]}, {'A':2,'B':2,'C':2,'D':2,'E':[1,2,3]}]

I want to get this result:

{'A': 4, 'B': 5, 'C': 6, 'D': 7, 'E':[3,6,9]}

CodePudding user response:

If you can not use numpy you can try this:

(using collections.defaultdict)

from collections import defaultdict
list_of_dicts = [{'A':1,'B':2,'C':3,'D':4,'E':[1,2,3]}, 
                 {'A':1,'B':1,'C':1,'D':1,'E':[1,2,3]}, 
                 {'A':2,'B':2,'C':2,'D':2,'E':[1,2,3]}]

dct = defaultdict(list)
for l in list_of_dicts:
    for k,v in l.items():
        dct[k].append(v)
        
for k,v in dct.items():
    if isinstance(v[0],list):
        dct[k] = [sum(x) for x in zip(*v)]
    else:
        dct[k] = sum(v)

Output:

>>> dct
defaultdict(list, {'A': 4, 'B': 5, 'C': 6, 'D': 7, 'E': [3, 6, 9]})

If you can use numpy you can try this:

import numpy as np

dct = defaultdict(list)
for l in list_of_dicts:
    for k,v in l.items():
        dct[k].append(v)

for k,v in dct.items():
    dct[k] = (np.array(v).sum(axis=0))

Output:

>>> dct
defaultdict(list, {'A': 4, 'B': 5, 'C': 6, 'D': 7, 'E': array([3, 6, 9])})
  • Related