繁体   English   中英

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

[英]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 s(如果有[1,2] == [2,1,2]则使用set s):

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))

Output:

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

暂无
暂无

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

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