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!

3
  • 1
    Use nested loops. Commented May 14, 2021 at 16:03
  • Yes,sir I agree with you and will update,thank you for your reminding! Commented May 14, 2021 at 16:29
  • Hi@Barmar,I just edited my question, please give me some suggestion, thank you so much! Commented May 14, 2021 at 16:37

3 Answers 3

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']}}
Sign up to request clarification or add additional context in comments.

5 Comments

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 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
Yes,it works!I really appreciate your help and knowledge!
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.
Hi @Ajax1234 can you help me with this question stackoverflow.com/questions/67576668/…
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'}}

2 Comments

Thank you for your reply, what if I have 10 dicts need to update?
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 }.
0
d = {}
d.setdefault("a", []) = 1
d.setdefault("a", []) = 2
d

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.