Dictdiffer
Dictdiffer is a Python library designed to compute differences between dictionaries and apply patches based on those differences. It handles nested structures, lists, and sets. The current version is 0.9.0, with releases occurring on an as-needed basis.
Warnings
- breaking Dictdiffer v0.9.0 dropped support for Python versions older than 3.5. Ensure your environment meets this minimum requirement when upgrading.
- breaking In v0.7.0, `dictdiffer` started using `deepcopy` internally for all diff operations to prevent results from referencing parts of the original structures. This change ensures that diff objects are immutable and do not change if the original dictionaries are modified later, but it alters previous behavior where direct references might have existed.
- gotcha Prior to v0.7.1, dictionary keys containing dots (`.`) could cause unexpected behavior or errors during diff operations. While fixed in v0.7.1, users on older versions should be aware of this limitation.
- gotcha Versions prior to v0.8.1 contained a bug that could lead to invalid diff output when comparing sets. This resulted in incorrect patch instructions for set differences.
Install
-
pip install dictdiffer
Imports
- diff
from dictdiffer import diff
- patch
from dictdiffer import patch
- revert
from dictdiffer import revert
- swap
from dictdiffer import swap
- DictDiffer
from dictdiffer import DictDiffer
Quickstart
from dictdiffer import diff, patch, revert
# Example dictionaries
old = {'a': 1, 'b': {'c': 2, 'd': [3, 4]}}
new = {'a': 10, 'b': {'c': 2, 'd': [3, 5]}, 'e': 6}
# Compute the diff
delta = list(diff(old, new))
print(f"Diff operations: {delta}")
# Apply the patch to the old dictionary
patched_dict = patch(delta, old)
print(f"Patched dictionary: {patched_dict}")
# Revert the patch from the new dictionary
reverted_dict = revert(delta, new)
print(f"Reverted dictionary: {reverted_dict}")
# Example with ignoring keys
old_ignore = {'name': 'Alice', 'version': '1.0', 'data': [1,2]}
new_ignore = {'name': 'Alice', 'version': '1.1', 'data': [1,2]}
ignored_delta = list(diff(old_ignore, new_ignore, ignore=['version']))
print(f"Diff ignoring 'version': {ignored_delta}")