如何比较两个字典里面的列表?

How to compare two dictionaries with lists inside?

我有两部词典,例如:

first = { 'test' :  [1, 2, 3] }
second = { 'test' :  [3, 2, 1] }

first == second  # False

有没有办法比较这两个字典并忽略其中列表中值的顺序?

我尝试使用 OrderedDict 但它没有用:

from collections import OrderedDict

first = OrderedDict({ 'test' :  [1, 2, 3] })
second = OrderedDict({ 'test' :  [3, 2, 1] })

first == second  # False

Counter 个列表(或 set 个,如果您有 [1,2] == [2,1,2] 个)用于包含的列表:

from collections import Counter

first = { 'test' :  [1, 2, 3] }
second = { 'test' :  [3, 2, 1] }
third = { 'test' :  [3, 2, 1], "meh":"" }

def comp_dict(d1,d2):
    return d1.keys() == d2.keys() and all(Counter(d1[k]) == Counter(d2[k]) for k in d1)
    # or 
    # return d1.keys() == d2.keys() and all(set(d1[k]) == set(d2[k]) for k in d1)

print(comp_dict(first, second))
print(comp_dict(first, third))

输出:

True
False

我找到了这个解决方案:

import unittest

class TestClass(unittest.TestCase):

    def test_count_two_dicts(self, d1, d2):
        self.assertCountEqual(d1, d2)

if __name__ == '__main__':
    first = { 'test' :  [1, 2, 3] }
    second = { 'test' :  [3, 2, 1] }
    
    t = TestClass()
    t.test_count_two_dicts(d1=first, d2=second)

如果你想比较两个字典(真或假)

first = { 'test' : [1, 2, 3] }

second = { 'test' : [3, 2, 1] }

is_equal = first == second

is_equal