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}] }
Advertisement
Answer
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.