Reputation: 4030
I have 2 nested dictionaries:
grouped1 ={'LabelStat': { 'Carrier': ['1', '1'],
'FormID': ['0201', '0430']},
'McAfee': {'DatDate': 'Not Available',
' DatVersion': 'Not Available'}
}
grouped2 ={'LabelStat': {'Carrier': ['2', '2'],
'FormID': ['10201', '10430']},
'McAfee': {'DatDate': 'Available',
'DatVersion': 'Available',}
}
And I want to append these 2 dictionaries,the output should looks like this:
com_grouped = {
'LabelStat': {'Carrier': ['1', '1','2','2'],
'FormID': ['0201', '0430','10201', '10430']}
'McAfee': {'DatDate': ['Not Available','Available']
'DatVersion': ['Not Available','Available']}
}
First tried:
com_grouped = grouped1.update(grouped2)
print(com_grouped)
And out put is none.
Then I tired:
com_grouped = grouped1
com_grouped=com_grouped.update(grouped2)
print(com_grouped)
Out put is still none!
Upvotes: 1
Views: 641
Reputation: 81
d = {}
d.setdefault("a", []) = 1
d.setdefault("a", []) = 2
d
OUT: {"a":[1, 2]}
Upvotes: 0
Reputation: 71451
You can use recursion with collections.defaultdict
:
from collections import defaultdict
import re
def merge(*d):
v = defaultdict(list)
for i in d:
for a, b in i.items():
v[re.sub('^\s+', '', a)].append(b)
return {a:merge(*b) if all(isinstance(j, dict) for j in b)
else [i for j in b for i in (j if isinstance(j, list) else [j])]
for a, b in v.items()}
print(merge(grouped1, grouped2))
Output:
{'LabelStat': {'Carrier': ['1', '1', '2', '2'], 'FormID': ['0201', '0430', '10201', '10430']}, 'McAfee': {'DatDate': ['Not Available', 'Available'], 'DatVersion': ['Not Available', 'Available']}}
Upvotes: 1
Reputation: 553
You can merge 2 dict with the update()
method:
grouped1 = {'LabelStat': {'Carrier': ['1', '1'],
'FormID': ['0201', '0430']},
'McAfee': {'DatDate': 'Not Available',
' DatVersion': 'Not Available'}
}
grouped2 = {'LabelStat': {'Carrier': ['2', '2'],
'FormID': ['10201', '10430']},
'McAfee': {'DatDate': 'Available',
'DatVersion': 'Available', }
}
com_grouped = grouped1
com_grouped.update(grouped2)
Output:
{'LabelStat': {'Carrier': ['2', '2'], 'FormID': ['10201', '10430']}, 'McAfee': {'DatDate': 'Available', 'DatVersion': 'Available'}}
Upvotes: 1