这个问题不同于其他的字典合并问题,因为冲突的重复项应该失败或返回False。其他解决方案使用优先规则来决定如何管理当一个键可能映射到两个不同的变量时应该怎么做。
我如何在Python中高效地合并两个字典。例如,考虑以下内容:
d1 = {'x': 'a', 'y': 'b', 'z': 'c'}
d2 = {'z': 'c', 'w': 'r'}
d3 = {'z': 'd', 'w': 'r'}
所以,合并字典1和2的结果将会是:
{'x': 'a', 'y': 'b', 'z': 'c', 'w': 'r'}
但是将1和3或2和3合并应该失败,因为z
存在冲突。
我的解决方案是:
def merge_dicts(d1,d2):
k1=d1.keys()
k2=d2.keys()
unified_dict=dict()
for k in k1:
# look up in second dictionary
if k in k2:
pt=d2[k] #pt stands for 'plain text'
# if lookup is a contradiction, return empty dictionary
# don't even bother with partial results
if pt!=d1[k]:
return dict()
else:
unified_dict[k]=d1[k] # safe: key is consistent
else:
unified_dict[k]=d1[k] # safe: no key in k2
# get the rest
# already resolved intersection issues so just get set difference
for k in d2.keys():
if k not in d1.keys():
unified_dict[k]=d2[k]
return unified_dict
有任何改进吗?
dict(d1, **d2)
,请参阅Python参数中的双星号(*)和单星号()有什么作用?以及dict()
函数文档。dict(d1)
仅创建d1
的副本。dict(**d2)
会以迂回的方式创建d2
的副本。dict(d1, **d2)
创建d1
的副本,并添加d2
的键值对。 - Martijn Pieters