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:
JavaScript
x
7
1
data = [
2
{'Supplement': {'label': 'Protein - 25.0', 'value': 1}},
3
{'Fruit and vegetable': {'label': 'Test - 100.0', 'value': 2}},
4
{'Fruit and vegetable': {'label': 'Peach - 10.0', 'value': 3}},
5
{'Protein': {'label': 'Yakiniku - 100.0', 'value': 4}}
6
]
7
Expected Results:
JavaScript
1
6
1
data_merged = {
2
'Supplement': [ {'label': 'Protein - 25.0', 'value': 1}],
3
'Fruit and vegetable': [{'label': 'Test - 100.0', 'value': 2}, {'label': 'Peach - 10.0', 'value': 3}],
4
'Protein': [{'label': 'Yakiniku - 100.0', 'value': 4}]
5
}
6
Advertisement
Answer
You can do this by looping over the lists and dictionaries. Like this:
JavaScript
1
16
16
1
import collections
2
3
data = [
4
{'Supplement': {'label': 'Protein - 25.0', 'value': 1}},
5
{'Fruit and vegetable': {'label': 'Test - 100.0', 'value': 2}},
6
{'Fruit and vegetable': {'label': 'Peach - 10.0', 'value': 3}},
7
{'Protein': {'label': 'Yakiniku - 100.0', 'value': 4}}
8
]
9
10
res = collections.defaultdict(lambda: [])
11
for dct in data:
12
for key in dct:
13
res[key].append(dct[key])
14
15
print(dict(res))
16
This will also work for dictionaries with multiple keys, unlike the other answer.