由于似乎没有人提及deepdiff
,因此出于完整性考虑,我将在此处添加。我发现通常获取(嵌套)对象的差异非常方便:
安装
pip install deepdiff
样例代码
import deepdiff
import json
dict_1 = {
"a": 1,
"nested": {
"b": 1,
}
}
dict_2 = {
"a": 2,
"nested": {
"b": 2,
}
}
diff = deepdiff.DeepDiff(dict_1, dict_2)
print(json.dumps(diff, indent=4))
输出量
{
"values_changed": {
"root['a']": {
"new_value": 2,
"old_value": 1
},
"root['nested']['b']": {
"new_value": 2,
"old_value": 1
}
}
}
关于漂亮地打印结果以供检查的注意事项:如果两个字典具有相同的属性键(与示例中的属性值可能不同),则上述代码有效。但是,如果存在"extra"
属性是dict之一,则json.dumps()
失败并显示
TypeError: Object of type PrettyOrderedSet is not JSON serializable
解决方案:使用diff.to_json()
和json.loads()
/ json.dumps()
漂亮打印:
import deepdiff
import json
dict_1 = {
"a": 1,
"nested": {
"b": 1,
},
"extra": 3
}
dict_2 = {
"a": 2,
"nested": {
"b": 2,
}
}
diff = deepdiff.DeepDiff(dict_1, dict_2)
print(json.dumps(json.loads(diff.to_json()), indent=4))
输出:
{
"dictionary_item_removed": [
"root['extra']"
],
"values_changed": {
"root['a']": {
"new_value": 2,
"old_value": 1
},
"root['nested']['b']": {
"new_value": 2,
"old_value": 1
}
}
}
替代方案:use pprint
,导致格式不同:
import pprint
# same code as above
pprint.pprint(diff, indent=4)
输出:
{ 'dictionary_item_removed': [root['extra']],
'values_changed': { "root['a']": { 'new_value': 2,
'old_value': 1},
"root['nested']['b']": { 'new_value': 2,
'old_value': 1}}}
x == y
根据stackoverflow.com/a/5635309/186202