考虑两个python字典:
>>> a = {'one': 10, 'two': 10.1, 'three': {'x': '10'}}
>>> b = {'one': 20, 'two': 20.1, 'three': {'x': '20'}}
很显然,两个字典a == b
的比较将得出False
,但是,值的数据类型都相同。
比较两个字典的值的数据类型的最简单方法是什么?是否有现有的python库可以执行相同的操作。
角落案例:
答案 0 :(得分:3)
看看deepdiff
模块。
安装:pip install deepdiff
用法示例:
from deepdiff import DeepDiff
a = {'one': 10, 'three': {'x': '10'}, 'two': '10.1'}
b = {'one': 10, 'three': {'x': '10'}, 'two': '10.1'}
i = {'one': 10, 'two': '10.1', 'three': {'x': '10'}}
j = {'one': 20, 'two': '20.1', 'three': {'x': '20'}}
m = {'one': 10, 'three': {'x': 10}, 'two': '10.1'}
n = {'one': 20, 'two': '20.1', 'three': {'x': '20'}}
ddiff1 = DeepDiff(a, b, ignore_order=True)
ddiff2 = DeepDiff(i, j, ignore_order=True)
ddiff3 = DeepDiff(m, n, ignore_order=True)
print(f"{ddiff1}\n{'type_changes' in ddiff1}\n")
print(f"{ddiff2}\n{'type_changes' in ddiff2}\n")
print(f"{ddiff3}\n{'type_changes' in ddiff3}\n")
输出:
{} False {'values_changed': {"root['two']": {'new_value': '20.1', 'old_value': '10.1'}, "root['three']['x']": {'new_value': '20', 'old_value': '10'}, "root['one']": {'new_value': 20, 'old_value': 10}}} False {'type_changes': {"root['three']['x']": {'old_type': <class 'int'>, 'new_type': <class 'str'>, 'old_value': 10, 'new_value': '20'}}, 'values_changed': {"root['one']": {'new_value': 20, 'old_value': 10}, "root['two']": {'new_value': '20.1', 'old_value': '10.1'}}} True