Python Deep比较两个字典的值的数据类型

时间:2019-05-04 08:21:38

标签: python dictionary types

考虑两个python字典:

>>> a = {'one': 10, 'two': 10.1, 'three': {'x': '10'}}
>>> b = {'one': 20, 'two': 20.1, 'three': {'x': '20'}}

很显然,两个字典a == b的比较将得出False,但是,值的数据类型都相同。

比较两个字典的值的数据类型的最简单方法是什么?是否有现有的python库可以执行相同的操作。

角落案例

  • 如果值本身是字典,则该解决方案必须递归比较
  • 仅需要类型的精确对等(int!= float)

1 个答案:

答案 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