2

Tried to google how to merge multiple dictionaries, but could not find a solution to merge values under same key in a dictionary. Although the original data is list, the expected results should be dictionary. I am stacked here, and hope someone show me a way to get resolve this.

Original Data:

data = [
 {'Supplement': {'label': 'Protein - 25.0', 'value': 1}}, 
 {'Fruit and vegetable': {'label': 'Test - 100.0', 'value': 2}},
 {'Fruit and vegetable': {'label': 'Peach - 10.0', 'value': 3}}, 
 {'Protein': {'label': 'Yakiniku - 100.0', 'value': 4}}
]

Expected Results:

data_merged = {
    'Supplement': [ {'label': 'Protein - 25.0', 'value': 1}],
    'Fruit and vegetable': [{'label': 'Test - 100.0', 'value': 2}, {'label': 'Peach - 10.0', 'value': 3}],
    'Protein': [{'label': 'Yakiniku - 100.0', 'value': 4}]
    }
tat
  • 45
  • 4

2 Answers2

2

You can do this by looping over the lists and dictionaries. Like this:

import collections

data = [
 {'Supplement': {'label': 'Protein - 25.0', 'value': 1}}, 
 {'Fruit and vegetable': {'label': 'Test - 100.0', 'value': 2}},
 {'Fruit and vegetable': {'label': 'Peach - 10.0', 'value': 3}}, 
 {'Protein': {'label': 'Yakiniku - 100.0', 'value': 4}}
]

res = collections.defaultdict(lambda: [])
for dct in data:
    for key in dct:
        res[key].append(dct[key])

print(dict(res))

This will also work for dictionaries with multiple keys, unlike the other answer.

Michael M.
  • 10,486
  • 9
  • 18
  • 34
  • 2
    I'm sure you probably already know, and it could be better to keep it as it is now for learning purposes or clarity, @Michael M., but when `defaultdict` is lacking a key it will call whatever callable has been passed as argument to the constructor (basically, it'll take the first arg, will run it with `arg()` and alehoop!) Since the built-in `list` constructor fits that description (is a callable and doesn't need any arguments) you can just do: `res = collections.defaultdict(list)`, and it will work. Pretty neat! – Savir Oct 28 '22 at 03:42
0

Python doesn't provide a built in way to merge the dictionaries like you want it to, you would just have to quickly loop through it all and add it.

new_data = {}

for i in data:
    if not new_data[i]:
        new_data[i] = [data[i]
    else:
        new_data[i] += [data[i]]

This should suffice

Leg3ndary
  • 193
  • 1
  • 4