如何使用 DeepDiff 获取 root

How to get root using DeepDiff

我目前正在使用 DeepDiff,我正在尝试弄清楚如何获取根的值而不是打印出根,例如

Value of root['hello'][0]['hello_world'] changed from "15251" to "51251".

所以我做了一个简单的脚本

from deepdiff import DeepDiff

dict_a = {'hello': [{'what': 'uh', 'hello_world': '15251'}]}
dict_b = {'hello': [{'hello_world': '51251', 'what': 'uh'}]}

t = DeepDiff(dict_a, dict_b, ignore_order=True)
print(t.pretty())

>>> Value of root['hello'][0]['hello_world'] changed from "15251" to "51251".

我想要的输出是我希望它能够打印出 root['hello'][0] 所以在我们的例子中是 dict_b['hello'][0] >>> {'hello_world': '51251', 'what': 'uh'} 所以我可以轻松地在 dict_b 中跟踪整个列表,而不仅仅是值

是否可以使用 DeepDiff 做到这一点?

您可以通过提供 view="tree" 作为参数来使用 tree-view 选项。然后你有 upt2 属性导航到第二个输入结构一侧的父级:

t = DeepDiff(dict_a, dict_b, ignore_order=True, view="tree")
for change in t["values_changed"]:
    print(change.up.t2)  # {'hello_world': '51251', 'what': 'uh'}