dictionary - Merge a dict in Python using 1 dict as base -
this question has answer here:
i looking feedback on python code. trying merge 2 dictionaries. 1 of dictionaries controls structure , default values, second dictionary overwrite default values when applicable.
please note looking following behaviour:
- keys present in other dict should not added
- nested dicts should taken account
i wrote simple function:
def merge_dicts(base_dict, other_dict): """ merge 2 dicts ensure base_dict remains , overwrite info other_dict """ out_dict = dict() key, value in base_dict.items(): if key not in other_dict: # use base nvalue = value elif isinstance(other_dict[key], type(value)): if isinstance(value, type({})): # new dict myst recursively merged nvalue = merge_dicts(value, other_dict[key]) else: # use others' value nvalue = other_dict[key] else: # error due difference of type raise typeerror('the type of key {} should {} (currently {})'.format( key, type(value), type(other_dict[key])) ) out_dict[key] = nvalue return out_dict
i sure can done more beautifully/pythonic.
"pythonicness" hard measure assess, here take on it:
def merge_dicts(base_dict, other_dict): """ merge 2 dicts ensure base_dict remains , overwrite info other_dict """ if other_dict none: return base_dict t = type(base_dict) if type(other_dict) != t: raise typeerror("mismatching types: {} , {}." .format(t, type(other_dict))) if not issubclass(t, dict): return other_dict return {k: merge_dicts(v, other_dict.get(k)) k, v in base_dict.items()}
example:
merge_dicts({"a":2, "b":{"b1": 5, "b2": 7}}, {"b": {"b1": 9}}) >>> {'a': 2, 'b': {'b1': 9, 'b2': 7}}
Comments
Post a Comment