I have 2 nested list:
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 a function will merge these 2 lists and it works:
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))
The output of this function is:
om_grouped = {
'LabelStat': {'Carrier': ['1', '1','2','2'],
'FormID': ['0201', '0430','10201', '10430']}
'McAfee': {'DatDate': ['Not Available','Available']
'DatVersion': ['Not Available','Available']}
}
So now the amount of dictionary is fixed, in the above I have 2,but what if the number will be dynamic, for example I will also have grouped3:
grouped3 ={'LabelStat': {'Carrier': ['3', '3'],
'FormID': ['102013', '104303']},
'McAfee': {'DatDate': 'Available3',
'DatVersion': 'Available3',}
}
My question how to modify merge function to make the parameter dynamic?
I have tried to put all the dictionary in a list:
dic_list = [grouped1,grouped2,grouped3]
And then use map function:
combin = map(merge,d_list)
print(combin)
for i in combin:
print(i)
But the out put is:
<map object at 0x000001AC43E7AF40>
{'LabelStat': {'Carrier': ['1', '1'], 'FormID': ['0201', '0430']}, 'McAfee': {'DatDate': ['Not Available'], 'DatVersion': ['Not Available']}}
{'LabelStat': {'Carrier': ['2', '2'], 'FormID': ['10201', '10430']}, 'McAfee': {'DatDate': ['Available'], 'DatVersion': ['Available']}}
{'LabelStat': {'Carrier': ['3', '3'], 'FormID': ['102013', '104303']}, 'McAfee': {'DatDate': ['Available3'], 'DatVersion': ['Available3']}}