Skip to content

Instantly share code, notes, and snippets.

@ton77v
Last active July 21, 2023 14:15
Show Gist options
  • Save ton77v/c84ac717e51dad03fd155dafb77ef8f4 to your computer and use it in GitHub Desktop.
Save ton77v/c84ac717e51dad03fd155dafb77ef8f4 to your computer and use it in GitHub Desktop.
deep merge nested dictionaries in Python
"""
Deep merging two dictionaries with any level of nesting.
Based on solution found at https://stackoverflow.com/a/71024248/7521470
Fixed a bug + mutability issue
"""
import copy
from unittest import TestCase
import pprint
pp = pprint.PrettyPrinter(indent=2)
def merge(source: dict, destination: dict) -> dict:
""" copies the items FROM SOURCE TO DESTINATION """
destination_copy = copy.deepcopy(destination)
for key, value in source.items():
destination_key_value = destination_copy.get(key)
if isinstance(value, dict) and isinstance(destination_key_value, dict):
destination_copy[key] = merge(value, destination_copy.setdefault(key, {}))
else:
destination_copy[key] = value
return destination_copy
class ModuleFuncsTests(TestCase):
def test_merge_dicts(self):
print('--test_merge_dicts--')
sub_cases = [
({'A': 'B'}, {'A': 'D'}, {'A': 'B'}),
({'A': True}, {'A': False}, {'A': True}),
({'A': {'B': 'C'}}, {'A': False}, {'A': {'B': 'C'}}),
({'first': {'all_rows': {'pass': 'dog', 'number': '1'}}},
{'first': {'all_rows': {'fail': 'cat', 'number': '5'}}},
{'first': {'all_rows': {'pass': 'dog', 'fail': 'cat', 'number': '1'}}}),
({'b': {'c': 1}}, {'b': 1}, {'b': {'c': 1}}),
({}, {'A (1)': {'B (2)': {'C (3)': [{'smth': 48, 'qwerty': 2}]}}},
{'A (1)': {'B (2)': {'C (3)': [{'smth': 48, 'qwerty': 2}]}}}),
({'A (1)': {'B (2)': {'D (3)': [{'bla-bla-bla': 1}]}}},
{'A (1)': {'D (3)': [{'bla-bla-bla': 1}]}},
{'A (1)': {'B (2)': {'D (3)': [{'bla-bla-bla': 1}]}, 'D (3)': [{'bla-bla-bla': 1}]}})
]
for s in sub_cases:
print('\n')
pp.pprint(s)
source, destination, control = s
res = merge(source, destination)
print(res)
with self.subTest(i=s):
self.assertDictEqual(res, control)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment