lib: Detect and show new keys in dict_diff

This commit is contained in:
Felix Uhl committed 2024-11-10 17:31:44 +01:00
1 parent b30e5ced5e
commit 4f16850ca4
2 files changed
+59 -5

No files matched your search

+29 -4
View File
@@ -1,8 +1,29 @@
from typing import Any
# Returns a dict that only contains the keys from `right` that have different values in `left`
def dict_diff(left: dict[str, Any], right: dict[str, Any]) -> dict[str, Any]:
"""Return a dict that only contains the keys and values of `right`
that are different from those in `left`.
>>> dict_diff({"a": 1, "b": 2}, {"a": 1, "b": 3})
{'b': 3}
Keys that are in `left` but not in `right` get the value `None`.
>>> dict_diff({"a": 1, "b": 2}, {"a": 1})
{'b': None}
Dicts are compared recursively.
>>> dict_diff({"a": {"b": 2}}, {"a": {"b": 3}})
{'a': {'b': 3}}
If a dict is missing in `left`, it gets the special key "_new" set
to True to differentiate it from a dict that was present but changed.
>>> dict_diff({"a": {"b": 1}}, {"a": {"b": 3}, "c": {"d": 4}})
{'a': {'b': 3}, 'c': {'d': 4, '_new': True}}
"""
new_dict: dict[str, Any] = {}
for k, right_val in right.items():
@@ -10,14 +31,18 @@ def dict_diff(left: dict[str, Any], right: dict[str, Any]) -> dict[str, Any]:
if left_val == right_val:
continue
if isinstance(right_val, dict):
new_dict[k] = dict_diff(left.get(k, {}), right[k])
else:
if not isinstance(right_val, dict):
new_dict[k] = right[k]
continue
new_dict[k] = dict_diff(left.get(k, {}), right[k])
if not left_val:
new_dict[k]["_new"] = True
for k, left_val in left.items():
if k not in right:
# Do not recurse, even if left_val is a dict!
# Recursion is already done in the first loop.
new_dict[k] = None
return new_dict
+30 -1
View File
@@ -99,6 +99,9 @@ def test_dict_diff_nested() -> None:
"h": 4,
"i": 5,
},
"o": {
"p": 6,
},
}
assert dict_diff(left, right) == {
"a": {
@@ -111,6 +114,10 @@ def test_dict_diff_nested() -> None:
"i": 5,
},
"k": None,
"o": {
"p": 6,
"_new": True,
},
}
assert dict_diff(right, left) == {
"a": {
@@ -125,8 +132,11 @@ def test_dict_diff_nested() -> None:
"k": {
"l": {
"m": 5,
"_new": True,
},
"_new": True,
},
"o": None,
}
assert dict_diff(left, left) == {}
assert dict_diff(right, right) == {}
@@ -135,4 +145,23 @@ def test_dict_diff_nested() -> None:
"g": None,
"k": None,
}
assert dict_diff({}, right) == right
assert dict_diff({}, right) == {
"a": {
"b": {
"c": 1,
"d": 3,
"_new": True,
},
"e": 3,
"_new": True,
},
"g": {
"h": 4,
"i": 5,
"_new": True,
},
"o": {
"p": 6,
"_new": True,
},
}