python-benedict/benedict/core/merge.py

31 lines
933 B
Python
Raw Normal View History

# -*- coding: utf-8 -*-
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):
overwrite = kwargs.get('overwrite', True)
2020-12-09 10:03:03 +00:00
concat = kwargs.get('concat', False)
others = [other] + list(args)
for other in others:
_merge_dict(d, other, overwrite=overwrite, concat=concat)
return d