Python 是否对AsserCountEqual中的列表使用AsserCountEqual?

Python 是否对AsserCountEqual中的列表使用AsserCountEqual?,python,python-unittest,Python,Python Unittest,我不熟悉单元测试,我正在尝试运行一个测试来检查两个字典是否相同,而不考虑值中元素的顺序。当我尝试时: import unittest dic1 = {'key': [1,2]} dic2 = {'key': [2,1]} class TestExample (unittest.TestCase): def test_dicEqual(self): self.assertDictEqual(dic1, dic2) tester = TestExample() tester.test_

我不熟悉单元测试,我正在尝试运行一个测试来检查两个字典是否相同,而不考虑值中元素的顺序。当我尝试时:

import unittest
dic1 = {'key': [1,2]}
dic2 = {'key': [2,1]}

class TestExample (unittest.TestCase):

def test_dicEqual(self):
    self.assertDictEqual(dic1, dic2)

tester = TestExample()
tester.test_dicEqual()
我得到:

AssertionError                            Traceback (most recent call last)
AssertionError: {'key': [1, 2]} != {'key': [2, 1]}
- {'a': [1, 2]}
?         ---

+ {'a': [2, 1]}
?        +++
有没有办法在不考虑顺序的情况下检查词典的内容?现在,我提出的解决方案是迭代字典的键:

def test_dictequal_iterate(self):
    for key, value in dic1 :
        self.assertCountEqual(value, dic2[key])

但此解决方案返回的概述不如assertDictEqual清晰。

我不确定这是最好的方法,但您可能可以尝试以下方法:

import unittest
from collections import Counter
dic1 = {'key': [1, 2]}
dic2 = {'key': [2, 1]}
dic3 = {'key': [1, 3]}
class TestExample (unittest.TestCase):
    def countize_dict(self, d):
        return {k:Counter(v) for k, v in d.items()}
    def assertDictEqualCountized(self, d1, d2):
        self.assertDictEqual(self.countize_dict(d1),
                             self.countize_dict(d2))
    def test_dicEqual(self):
        self.assertDictEqualCountized(dic1, dic2)
    def test_other_dic_equal(self):
        self.assertDictEqualCountized(dic1, dic3)



tester = TestExample()
tester.test_dicEqual() # pass
tester.test_other_dic_equal() # fail

AssertionError: {'key': Counter({1: 1, 2: 1})} != {'key': Counter({1: 1, 3: 1})}
- {'key': Counter({1: 1, 2: 1})}
?                        ^

+ {'key': Counter({1: 1, 3: 1})}
?                        ^