Skip to content
Advertisement

How to append lists in nested dictionary in Python

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!

Advertisement

Answer

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']}}
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement