0

I have got a list of dictionaries,

_list = [
    {"a": [1, 20, 20, 40], "b": [0, 14, 14, 28]},
    {"a": [2, 20, 20, 40], "b": [2, 14, 14, 28]},
    {"c": [1, 20, 20, 40], "d": [0, 14, 14, 28]},
]

I want to merge these dict and get a single dict, I want their values which are lists to be merged if the key is same and I expect the final result like this:

_dict = {
    "a": [3, 40, 40, 80], 
    "b": [2, 28, 28, 56], 
    "c": [1, 20, 20, 40], 
    "d": [0, 14, 14, 28]
    }

I have no idea where to start and what approach to follow, can you please help me to get the desired output? Thanks

  • Very similar to https://stackoverflow.com/questions/66411153/sum-dictionary-values-using-two-keys-as-index-how-to-achieve-this/66412584#66412584. Would that solve your problem? – Thymen Jun 24 '21 at 12:59

2 Answers2

1

This is a basic solution, no the most efficient but works:

_list = [
  {"a": [1, 20, 20, 40], "b": [0, 14, 14, 28]},
  {"a": [2, 20, 20, 40], "b": [2, 14, 14, 28]},
  {"c": [1, 20, 20, 40], "d": [0, 14, 14, 28]},
]


_dict = {}

for dict_item in _list:
  for key, value in dict_item.items():
    if key in _dict:
      val = [a + b for a, b in zip(_dict[key], value)]
      _dict[key] = val
    else:
      _dict[key] = value

print(_dict)
aurelien_morel
  • 444
  • 3
  • 14
0

Here is a solution with Pandas:

import pandas as pd

m=[{k:np.array(v) for k,v in i.items()} for i in _list]
df=pd.DataFrame(m)
df=df.fillna(0)
_dict = {i:list(sum(df[i])) for i in df.columns}

print(_dict)

Output:

{'a': [3, 40, 40, 80], 'b': [2, 28, 28, 56], 'c': [1, 20, 20, 40], 'd': [0, 14, 14, 28]}
IoaTzimas
  • 10,538
  • 2
  • 13
  • 30