python-benedict/benedict/core/merge.py

29 lines
908 B
Python
Raw Permalink Normal View History

from benedict.utils import type_util
2020-12-09 10:03:03 +00:00
def _merge_dict(d, other, overwrite=True, concat=False):
2020-02-05 09:30:19 +00:00
for key, value in other.items():
_merge_item(d, key, value, overwrite=overwrite, concat=concat)
2020-02-05 09:30:19 +00:00
2020-12-09 10:03:03 +00:00
def _merge_item(d, key, value, overwrite=True, concat=False):
if key in d:
item = d.get(key, None)
if type_util.is_dict(item) and type_util.is_dict(value):
_merge_dict(item, value, overwrite=overwrite, concat=concat)
2020-12-09 10:03:03 +00:00
elif concat and type_util.is_list(item) and type_util.is_list(value):
item += value
elif overwrite:
d[key] = value
2020-02-05 09:30:19 +00:00
else:
d[key] = value
def merge(d, other, *args, **kwargs):
2022-02-13 10:35:43 +00:00
overwrite = kwargs.get("overwrite", True)
concat = kwargs.get("concat", False)
others = [other] + list(args)
for other in others:
_merge_dict(d, other, overwrite=overwrite, concat=concat)
return d