I have 2 nested dictionaries:
JavaScript
x
14
14
1
grouped1 ={'LabelStat': { 'Carrier': ['1', '1'],
2
'FormID': ['0201', '0430']},
3
4
'McAfee': {'DatDate': 'Not Available',
5
' DatVersion': 'Not Available'}
6
}
7
8
9
grouped2 ={'LabelStat': {'Carrier': ['2', '2'],
10
'FormID': ['10201', '10430']},
11
'McAfee': {'DatDate': 'Available',
12
'DatVersion': 'Available',}
13
}
14
And I want to append these 2 dictionaries,the output should looks like this:
JavaScript
1
9
1
com_grouped = {
2
'LabelStat': {'Carrier': ['1', '1','2','2'],
3
'FormID': ['0201', '0430','10201', '10430']}
4
5
'McAfee': {'DatDate': ['Not Available','Available']
6
'DatVersion': ['Not Available','Available']}
7
8
}
9
First tried:
JavaScript
1
3
1
com_grouped = grouped1.update(grouped2)
2
print(com_grouped)
3
And out put is none.
Then I tired:
JavaScript
1
4
1
com_grouped = grouped1
2
com_grouped=com_grouped.update(grouped2)
3
print(com_grouped)
4
Out put is still none!
Advertisement
Answer
You can use recursion with collections.defaultdict
:
JavaScript
1
13
13
1
from collections import defaultdict
2
import re
3
def merge(*d):
4
v = defaultdict(list)
5
for i in d:
6
for a, b in i.items():
7
v[re.sub('^s+', '', a)].append(b)
8
return {a:merge(*b) if all(isinstance(j, dict) for j in b)
9
else [i for j in b for i in (j if isinstance(j, list) else [j])]
10
for a, b in v.items()}
11
12
print(merge(grouped1, grouped2))
13
Output:
JavaScript
1
2
1
{'LabelStat': {'Carrier': ['1', '1', '2', '2'], 'FormID': ['0201', '0430', '10201', '10430']}, 'McAfee': {'DatDate': ['Not Available', 'Available'], 'DatVersion': ['Not Available', 'Available']}}
2