This question differs from similar dictionary merge questions in that conflicting duplicates should fail, or return False. Other solutions use a precedence rule to decide how to manage when one key might be mapped to two different variables.
How do I merge two dicts efficiently in python. As an example, consider:
d1 = {'x': 'a', 'y': 'b', 'z': 'c'}
d2 = {'z': 'c', 'w': 'r'}
d3 = {'z': 'd', 'w': 'r'}
so, the result of merging dictionary 1 and 2 would be
{'x': 'a', 'y': 'b', 'z': 'c', 'w': 'r'}
but the merge of 1 and 3 or 2 and 3 should fail because z
has a conflict.
My solution is:
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
Any improvements?