Skip to content

Instantly share code, notes, and snippets.

@pando85

pando85/merge_dict.py

Last active Feb 11, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.