繁体   English   中英

两个嵌套字典的单元测试相等性

[英]Unittest equality of two nested dictionaries

如果我想比较其中包含值list的 2 个字典,我应该使用哪个assert语句。

例如,如果这些字典是这样的:

{'other_parts': ['director', 'head', 'chief', 'leader', 'administrator'], 'headword': 'manager', 'language': 'en'}

{'other_parts': ['director', 'chief', 'head', 'leader', 'administrator'], 'headword': 'manager', 'language': 'en'}

我希望通过这两个字典的比较,因为我不关心嵌套列表中的顺序。 assertDictEqual ,与assertDictEqual比较失败了,因为other_parts嵌套列表的顺序不同。

如果您不关心顺序,则必须对列表进行排序或使用集合(仅当您确定列表不包含重复项时!)

dict1['other_parts'] = sorted(dict1['other_parts'])
dict2['other_parts'] = sorted(dict2['other_parts'])
assertDictEqual(dict1, dict2)

也可以用作

from unittest import TestCase
TestCase().assertEqual(dict1, dict2)

请参阅文档: https : //docs.python.org/3/library/unittest.html#unittest.TestCase.addTypeEqualityFunc

修改您的问题后,似乎AssertCountEqual就是您正在寻找的 - 正如文档中所述,它正是这样做的。 如果它不适用于整个结构,我会使用循环在每个内部列表上运行它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM