Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to merge two nested dict in python?

I have two nested dictionary data. I want to merge them to create one dictionary in python. Dictionary data :

dict1 = {'employee':{'dev1': 'Roy'}}
dict2 = {'employee':{'dev2': 'Biswas'}}

Now I trying to create a dictionary like bellow from them.Required Output

dict_output = {'employee':{
                    'dev1': 'Roy',
                    'dev2': 'Biswas'
                    }

       }

my try:

import json

dict1 = {'employee':{'dev1': 'Roy'}}
dict2 = {'employee':{'dev2': 'Biswas'}}

dict1.update(dict2)
print(json.dumps(dict1, indent=2))

Output:

{
  "employee": {
    "dev2": "Biswas"
  }
}

I am unable to merge both the dictionary.Need help to merge them

like image 893
Arijit Panda Avatar asked May 05 '17 05:05

Arijit Panda


1 Answers

You can just update the inner dictionary.

>>> dict1 = {'employee':{'dev1': 'Roy'}}
>>> dict2 = {'employee':{'dev2': 'Biswas'}}
>>> 
>>> for key in dict1:
...     if key in dict2:
...         dict1[key].update(dict2[key])
... 
>>> dict1
{'employee': {'dev2': 'Biswas', 'dev1': 'Roy'}}
like image 168
Ahsanul Haque Avatar answered Sep 23 '22 06:09

Ahsanul Haque