mergedeep
mergedeep is a Python library providing a deep merge function for dictionaries and other mutable mappings. It offers flexible strategies for handling conflicts, including replacement (default), additive merging for collections like lists, and type-safe replacement. The current version is 1.3.4, and the library is actively maintained with regular releases.
Warnings
- gotcha By default, `mergedeep.merge` modifies the first dictionary (destination) in-place. If you need to preserve the original destination dictionary, pass an empty dictionary as the first argument to `merge`.
- gotcha The default merge strategy (`Strategy.REPLACE`) for lists, tuples, and sets is to replace the destination collection with the source collection. This differs from some other deep merge implementations that might concatenate or union lists by default.
- gotcha Using `Strategy.TYPESAFE_REPLACE` will raise a `TypeError` if the types of corresponding values in the destination and source dictionaries are different. This can be unexpected if you rely on implicit replacement even when types mismatch.
Install
-
pip install mergedeep
Imports
- merge
from mergedeep import merge
- Strategy
from mergedeep import merge, Strategy
Quickstart
from mergedeep import merge, Strategy
a = {'keyA': 1, 'nested': {'x': 10, 'list_data': [1, 2]}}
b = {'keyB': 2, 'nested': {'y': 20, 'list_data': [3, 4]}}
c = {'keyC': 3, 'nested': {'x': 100, 'new_list': [5]}}
# 1. Merge into a new dictionary (non-mutating)
merged_new = merge({}, a, b, c)
print(f"Merged into new: {merged_new}")
# Expected: {'keyA': 1, 'nested': {'x': 100, 'list_data': [3, 4], 'y': 20, 'new_list': [5]}, 'keyB': 2, 'keyC': 3}
# 2. Merge into an existing dictionary (mutating 'a')
merge(a, b, c)
print(f"Merged into existing 'a': {a}")
# Expected: {'keyA': 1, 'nested': {'x': 100, 'list_data': [3, 4], 'y': 20, 'new_list': [5]}, 'keyB': 2, 'keyC': 3}
# 3. Merging with an additive strategy for lists
dst_additive = {'items': [1, 2], 'counts': {'a': 1}}
src_additive = {'items': [3, 4], 'counts': {'b': 1}}
merged_additive = merge({}, dst_additive, src_additive, strategy=Strategy.ADDITIVE)
print(f"Merged with ADDITIVE strategy: {merged_additive}")
# Expected: {'items': [1, 2, 3, 4], 'counts': {'a': 1, 'b': 1}}