Deep Merge
Deep Merge is a lightweight Python utility for recursively merging dictionaries. It's designed for simplicity and handles nested dictionaries and lists with specific strategies. The current version is 0.0.4, with releases occurring periodically but not on a fixed schedule.
Common errors
-
AttributeError: module 'deep_merge' has no attribute 'merge'
cause Attempting to call `deep_merge.merge()` after `import deep_merge`.fixThe `merge` function is directly exposed. Use `from deep_merge import merge` and then call `merge()`. -
My original dictionary was modified unexpectedly after calling merge!
cause The `merge` function performs an in-place modification of the first argument (the 'target' dictionary).fixPass a copy of your dictionary if you wish to preserve the original: `merged_dict = merge(my_original_dict.copy(), other_dict)`. -
Lists are being appended, not truly merged (e.g., unique items not preserved).
cause The library's design for lists is to concatenate them (`target_list + source_list`), not to perform deep or intelligent merging of list elements.fixThis is expected behavior for `deep-merge`. If you require more sophisticated list merging, consider pre-processing your lists or using a library with configurable list merge strategies.
Warnings
- gotcha The `merge` function modifies the first dictionary (the 'target') in-place. It does not return a new dictionary unless the 'target' dictionary is a copy itself.
- gotcha When merging lists, `deep-merge` simply appends the source list to the target list. It does not perform any deep merging or unique item handling for list elements.
- gotcha Only dictionaries and lists have special merging logic. For other data types (e.g., integers, strings, tuples, sets), the value from the source dictionary will simply overwrite the value in the target dictionary.
Install
-
pip install deep-merge
Imports
- merge
import deep_merge; deep_merge.merge(...)
from deep_merge import merge
Quickstart
from deep_merge import merge
d1 = {'a': 1, 'b': {'c': 2}, 'list_key': [1, 2]}
d2 = {'b': {'d': 3}, 'e': 4, 'list_key': [3, 4]}
# NOTE: d1 will be modified in-place by the merge function.
# If you need to preserve d1, pass a copy: merge(d1.copy(), d2)
merged_dict = merge(d1, d2)
print(merged_dict)
# Expected output: {'a': 1, 'b': {'c': 2, 'd': 3}, 'list_key': [1, 2, 3, 4], 'e': 4}
# Note how 'list_key' lists are appended.