2017-05-05 90 views
1

我有兩個嵌套字典數據。我想合併它們以在python中創建一個字典。 字典數據:如何在Python中合併兩個嵌套的字典?

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

現在我想創建從中波紋管的字典。 所需的輸出

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

     } 

我嘗試:

import json 

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

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

輸出:

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

我無法合併兩個dictionary.Need幫助它們合併

回答

4

你可以ju st更新內部字典。

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

這裏的,如果兩個字典有不同的密鑰,並且要保持他們所有應該甚至工作的解決方案。

from collections import defaultdict 

dict1 = {'employee': {'dev1': 'Roy'}, 'aKeyNotInDict2': {}} 
dict2 = {'employee': {'dev2': 'Biswas'}, 'aKeyNotInDict1': {}} 
merged_dict = defaultdict(dict) 

merged_dict.update(dict1) 
for key, nested_dict in dict2.items(): 
    merged_dict[key].update(nested_dict) 

print(dict(merged_dict)) 

輸出:

{ 
    'employee': {'dev2': 'Biswas', 'dev1': 'Roy'}, 
    'aKeyNotInDict2': {}, 
    'aKeyNotInDict1': {} 
} 
0
#use a dict comprehension. Adding {} in get() is to set a default return value if the key doesn't exist in dict1 

{k:dict(dict1.get(k,{}).items() + v.items()) for k,v in dict2.items()} 
Out[689]: {'employee': {'dev1': 'Roy', 'dev2': 'Biswas'}} 

#Alternatively, a less readable way to merge the dicts using the dict constructor. 

{k:dict(dict1.get(k,{}), **v) for k,v in dict2.items()} 
Out[690]: {'employee': {'dev1': 'Roy', 'dev2': 'Biswas'}} 
0

```

[KEY1 == KEY2和dict1.get(KEY1).update(dict2.get(KEY2)),用於KEY1 ,KEY2在拉鍊(dict1,dict2)]

打印dict1

```