1

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']}}
William
  • 3,724
  • 9
  • 43
  • 76
  • Does this answer your question? [Pass a list to a function to act as multiple arguments](https://stackoverflow.com/questions/3480184/pass-a-list-to-a-function-to-act-as-multiple-arguments) – Pranav Hosangadi May 17 '21 at 20:36

1 Answers1

1

Simply use unpacking:

r = merge(*dic_list)

Output:

{'LabelStat': {'Carrier': ['1', '1', '2', '2', '3', '3'], 'FormID': ['0201', '0430', '10201', '10430', '102013', '104303']}, 'McAfee': {'DatDate': ['Not Available', 'Available', 'Available3'], 'DatVersion': ['Not Available', 'Available', 'Available3']}}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102