我正在尋找關於我的Python代碼的反饋。我正在試圖合併兩本字典。其中一個字典控制結構和默認值,第二個字典將在適用時覆蓋默認值。以1字典爲基礎合併Python中的字典
請注意,我要尋找以下行爲:
- 鍵只存在於其他字典應該不加入
- 嵌套類型的字典,應考慮到
我寫了這個簡單的功能:
def merge_dicts(base_dict, other_dict):
""" Merge two dicts
Ensure that the base_dict remains as is and overwrite info from other_dict
"""
out_dict = dict()
for key, value in base_dict.items():
if key not in other_dict:
# simply use the base
nvalue = value
elif isinstance(other_dict[key], type(value)):
if isinstance(value, type({})):
# a new dict myst be recursively merged
nvalue = merge_dicts(value, other_dict[key])
else:
# use the others' value
nvalue = other_dict[key]
else:
# error due to difference of type
raise TypeError('The type of key {} should be {} (currently is {})'.format(
key,
type(value),
type(other_dict[key]))
)
out_dict[key] = nvalue
return out_dict
我相信這可以做得更漂亮/ pythonic。
的'值鍵不在'base_dict'中。這是想要的行爲? –
因此''other_dict'中不在'base_dict'中的鍵應該被忽略,對吧? – jdehesa
問題不是重複的,至少不是這些問題;這裏必須考慮嵌套的字典。 – jdehesa