简体   繁体   中英

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!

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']}}

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'}}
d = {}
d.setdefault("a", []) = 1
d.setdefault("a", []) = 2
d

OUT: {"a":[1, 2]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM