Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@pando85
Last active February 11, 2020 08:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pando85/50973939caee285ddf5c48c10b3e9dc6 to your computer and use it in GitHub Desktop.
Save pando85/50973939caee285ddf5c48c10b3e9dc6 to your computer and use it in GitHub Desktop.
Python deep merge dict
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