【发布时间】:2018-01-04 14:03:33
【问题描述】:
我正在寻找有关我的 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。
【问题讨论】:
-
如果对应的key不在
base_dict中,则不会添加other_dict的值。这是想要的行为吗? -
所以
other_dict中不在base_dict中的键应该被忽略,对吧? -
这个问题不是重复的,至少不是那些问题;这里嵌套的
dicts 必须考虑在内。 -
是的,不应该添加额外的键。这是想要的行为。
-
是的,嵌套字典确实必须考虑在内。
标签: python dictionary nested