尝试使用 pytest 断言两个具有嵌套内容的 Python 字典相互相等(顺序无关)。有没有更符合 Python 风格的方法?
尝试使用 pytest 断言两个具有嵌套内容的 Python 字典相互相等(顺序无关)。有没有更符合 Python 风格的方法?
pytest的魔力非常聪明。只需编写:
assert {'a': {'b': 2, 'c': {'d': 4} } } == {'a': {'b': 2, 'c': {'d': 4} } }
您将进行一个嵌套的等式测试。
不要花费时间自己编写这个逻辑。只需使用默认测试库 unittest
提供的函数即可。
from unittest import TestCase
TestCase().assertDictEqual(expected_dict, actual_dict)
>>> d1 = {n: chr(n+65) for n in range(10)}
>>> d2 = {n: chr(n+65) for n in range(10)}
>>> d1 == d2
True
>>> l1 = [1, 2, 3]
>>> l2 = [1, 2, 3]
>>> d2[10] = l2
>>> d1[10] = l1
>>> d1 == d2
True
>>> class Example:
stub_prop = None
>>> e1 = Example()
>>> e2 = Example()
>>> e2.stub_prop = 10
>>> e1.stub_prop = 'a'
>>> d1[11] = e1
>>> d2[11] = e2
>>> d1 == d2
False
通用的方法是:
import json
# Make sure you sort any lists in the dictionary before dumping to a string
dictA_str = json.dumps(dictA, sort_keys=True)
dictB_str = json.dumps(dictB, sort_keys=True)
assert dictA_str == dictB_str
assert all(v == actual_dict[k] for k,v expected_dict.items()) and len(expected_dict) == len(actual_dict)
dict1==dict2
即可。而且为了严谨起见,如果需要逐项检查,则还需要遍历嵌套元素。 - user4396006is
运算符,它仅检查内存指针。 - user4396006你的问题不是很具体,但根据我理解,你要么想检查长度是否相同。
a = [1,5,3,6,3,2,4]
b = [5,3,2,1,3,5,3]
if (len(a) == len(b)):
print True
else:
print false
或者检查列表值是否相同
import collections
compare = lambda x, y: collections.Counter(x) == collections.Counter(y)
compare([1,2,3], [1,2,3,3])
print compare #answer would be false
compare([1,2,3], [1,2,3])
print compare #answer would be true
但是对于字典,您也可以使用
x = dict(a=1, b=2)
y = dict(a=2, b=2)
if(x == y):
print True
else:
print False
assert d1 == d2
吗?另外,你的嵌套内容是什么? - Szabolcs