Last active
February 11, 2020 08:59
-
-
Save pando85/50973939caee285ddf5c48c10b3e9dc6 to your computer and use it in GitHub Desktop.
Python deep merge dict
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pytest | |
def merge_dict(a, b): | |
for key in b: | |
if key in a: | |
if isinstance(a[key], dict) and isinstance(b[key], dict): | |
merge_dict(a[key], b[key]) | |
elif a[key] == b[key]: | |
pass | |
elif isinstance(a[key], list) and isinstance(b[key], list): | |
a[key] += b[key] | |
else: | |
raise Exception('Conflict') | |
else: | |
a[key] = b[key] | |
return a | |
def test_merge_dict(): | |
a = {'foo': 'boo'} | |
b = {'bar': 'zoo'} | |
expected_result = { | |
'foo': 'boo', | |
'bar': 'zoo' | |
} | |
result = merge_dict(a, b) | |
assert result == expected_result | |
def test_merge_dict_deep(): | |
a = { | |
'foo': { | |
'bar': 'boo', | |
} | |
} | |
b = { | |
'foo': { | |
'baz': 'zoo', | |
} | |
} | |
expected_result = { | |
'foo': { | |
'bar': 'boo', | |
'baz': 'zoo', | |
} | |
} | |
result = merge_dict(a, b) | |
assert result == expected_result | |
def test_merge_dict_list(): | |
a = { | |
'foo': [ | |
'boo' | |
] | |
} | |
b = { | |
'foo': [ | |
'baz' | |
] | |
} | |
expected_result = { | |
'foo': [ | |
'boo', | |
'baz', | |
] | |
} | |
result = merge_dict(a, b) | |
assert result == expected_result | |
def test_merge_dict_conflict(): | |
a = { | |
'foo': [ | |
'boo' | |
] | |
} | |
b = { | |
'foo': { | |
'baz': 'zoo', | |
} | |
} | |
with pytest.raises(Exception): | |
merge_dict(a, b) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment