Alon Barad
Alon Barad

Reputation: 1981

How to compare two dictionaries with lists inside?

I have two dictionaries, for example:

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

first == second  # False

Is there a way to compare these two dictionaries and ignore the order of the values in the lists inside?

I tried using OrderedDict but it didn't work:

from collections import OrderedDict

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

first == second  # False

Upvotes: 0

Views: 414

Answers (3)

Osama Ahmed
Osama Ahmed

Reputation: 1

If you want to compare both dicts (True or False)

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

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

is_equal = first == second

is_equal

Upvotes: 0

Alon Barad
Alon Barad

Reputation: 1981

I found this solution:

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)

Upvotes: 1

Patrick Artner
Patrick Artner

Reputation: 51653

Use Counters of your lists (or sets if you have [1,2] == [2,1,2]) for your contained lists:

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

Upvotes: 1

Related Questions