Fixed lists concat when merging nested dicts. #48

This commit is contained in:
Fabio Caccamo 2021-01-19 11:55:35 +01:00
parent 61e50666a7
commit 0ca7599841
2 changed files with 49 additions and 3 deletions

View File

@ -5,14 +5,14 @@ from benedict.utils import type_util
def _merge_dict(d, other, overwrite=True, concat=False):
for key, value in other.items():
_merge_item(d, key, value, overwrite, concat)
_merge_item(d, key, value, overwrite=overwrite, concat=concat)
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)
_merge_dict(item, value, overwrite=overwrite, concat=concat)
elif concat and type_util.is_list(item) and type_util.is_list(value):
item += value
elif overwrite:
@ -26,5 +26,5 @@ def merge(d, other, *args, **kwargs):
concat = kwargs.get('concat', False)
others = [other] + list(args)
for other in others:
_merge_dict(d, other, overwrite, concat)
_merge_dict(d, other, overwrite=overwrite, concat=concat)
return d

View File

@ -0,0 +1,46 @@
# -*- coding: utf-8 -*-
from benedict import benedict
import json
import unittest
class github_issue_0048_test_case(unittest.TestCase):
"""
https://github.com/fabiocaccamo/python-benedict/issues/48
To run this specific test:
- Run python -m unittest tests.github.test_issue_0048
"""
def test_json_dumps_with_cloned_instance(self):
test = benedict({
'foo': {
'bar': {
'foobar': {
'barbar': ['test'],
},
},
},
})
test2 = {
'foo': {
'bar': {
'foobar': {
'barbar': ['test2'],
},
},
},
}
test.merge(test2, overwrite=True, concat=True)
# print(test.dump())
self.assertEqual(test, {
'foo': {
'bar': {
'foobar': {
'barbar': ['test', 'test2'],
},
},
},
})