1

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!

William
  • 3,724
  • 9
  • 43
  • 76

3 Answers3

1

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']}}
Ajax1234
  • 69,937
  • 8
  • 61
  • 102
  • Hi Sir,thank you for your reply,but when I run it,the output of DatVersion is like this: DatVersion': ['Not Available'], 'DatVersion': ['Available']}} not combine together,can you help me check really appreciate! – William May 14 '21 at 16:18
  • @William That is because you have extra whitespace in front of `DatVersion` in `grouped1`: `' DatVersion'`. You can either adjust your original input or use my edited version which strips this leading whitespace from the keys – Ajax1234 May 14 '21 at 16:20
  • Yes,it works!I really appreciate your help and knowledge! – William May 14 '21 at 16:24
  • Hey @Ajax1234, would you mind adding a more newbie-friendly version of your solution without the use of complex list and dict comprehensions? I am sure if it is a bit more readable, folks can understand it better. – Savvy May 14 '21 at 19:59
  • Hi @Ajax1234 can you help me with this question https://stackoverflow.com/questions/67576668/python-how-to-looping-a-list-and-use-each-2-of-the-list-value-as-a-parameter – William May 17 '21 at 20:32
1

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'}}
Eitan Rosati
  • 543
  • 5
  • 18
  • Thank you for your reply, what if I have 10 dicts need to update? – William May 14 '21 at 16:13
  • As i know you can use a loop with that operation. or use this code(if you have all the names of the dicts): ```merged = {**dict1, **dict2,**dict3,**dict4,**dict5,**dict6,**dict7,**dict8,**dict9,**dict10 }```. – Eitan Rosati May 14 '21 at 16:23
0
d = {}
d.setdefault("a", []) = 1
d.setdefault("a", []) = 2
d

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

CoderCookie10
  • 81
  • 1
  • 10