this question differs similar dictionary merge questions in conflicting duplicates should fail, or return false. other solutions use precedence rule decide how manage when 1 key might mapped 2 different variables.
how merge 2 dicts efficiently in python. example, consider:
d1 = {'x': 'a', 'y': 'b', 'z': 'c'} d2 = {'z': 'c', 'w': 'r'} d3 = {'z': 'd', 'w': 'r'} so, result of merging dictionary 1 , 2 be
{'x': 'a', 'y': 'b', 'z': 'c', 'w': 'r'} but merge of 1 , 3 or 2 , 3 should fail because z has conflict.
my solution is:
def merge_dicts(d1,d2): k1=d1.keys() k2=d2.keys() unified_dict=dict() k in k1: # in second dictionary if k in k2: pt=d2[k] #pt stands 'plain text' # if lookup contradiction, return empty dictionary # don't bother partial results if pt!=d1[k]: return dict() else: unified_dict[k]=d1[k] # safe: key consistent else: unified_dict[k]=d1[k] # safe: no key in k2 # rest # resolved intersection issues set difference k in d2.keys(): if k not in d1.keys(): unified_dict[k]=d2[k] return unified_dict any improvements?
use dictionary views here; let treat dictionary keys sets:
def merge_dicts(d1, d2): try: # python 2 intersection = d1.viewkeys() & d2 except attributeerror: intersection = d1.keys() & d2 if any(d1[shared] != d2[shared] shared in intersection): return {} # empty result if there conflicts # leave rest c code, execute fast merge using dict() return dict(d1, **d2) the above code tests shared keys referencing non-matching values; merge best left dict() function.
i made function work both on python 2 , python 3; if need support 1 or other, remove try..except , replace intersection relevant expression. in python 3 dict.keys() method returns dictionary view default.
you conceivably make one-liner; python 3 version:
def merge_dicts(d1, d2): return {} if any(d1[k] != d2[k] k in d1.keys() & d2) else dict(d1, **d2) demo:
>>> d1 = {'x': 'a', 'y': 'b', 'z': 'c'} >>> d2 = {'z': 'c', 'w': 'r'} >>> d3 = {'z': 'd', 'w': 'r'} >>> merge_dicts(d1, d2) {'y': 'b', 'x': 'a', 'z': 'c', 'w': 'r'} >>> merge_dicts(d1, d3) {} >>> merge_dicts(d2, d3) {}
Comments
Post a Comment