Home > Back-end >  Merging values with a same key
Merging values with a same key

Time:10-28

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}]
    }

CodePudding user response:

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.

CodePudding user response:

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

  • Related