Home > Net >  compare two list of dictonary with different order in Python
compare two list of dictonary with different order in Python

Time:02-03

I have two lists of dict which I need to compare but dict in different order so I am not sure what is the correct way to do it.

l1 = [{'a': '1'}, {'b': '2'}]

l2 = [{'b': '2'}, {'a': '1'}]

result should be true when I compare l1 and l2 as both have same dictionaries in their respective list.

Thanks in advance

CodePudding user response:

Try:

l1 = [{'a': '1'}, {'b': '2'}]

l2 = [{'b': '2'}, {'a': '1'}]

if (all(item in l1 for item in l2) and all(item in l2 for item in l1)):
    print('TRUE')
else:
    print('FALSE')

CodePudding user response:

You can achieve it by list comprehension:

dict_1 = {"a": '1', "b": '2'}
dict_2 = {"b": '2', "a": '1'}
res = all((dict_2.get(k) == v for k, v in dict_1.items()))
print(res)

Output: True

CodePudding user response:

Sort the dict in the list and compare, we can get it

l1 = [{'a': '1'}, {'b': '2'}]
l2 = [{'b': '2'}, {'a': '1'}]

list_1 = sorted(l1, key=lambda k: list(k.values())[0])
list_2 = sorted(l2, key=lambda k: list(k.values())[0])

if list_1 == list_2:
    print("True")
else:
    print("False")

CodePudding user response:

To solve this in linear time complexity, you can convert each sub-dict to a frozenset of item tuples, convert each list to a set of such frozensets, so that you can efficiently compare the two lists of dicts by comparing the two converted sets of frozensets instead:

from operator import eq

print(eq(*(set(frozenset(map(tuple, d.items())) for d in l) for l in (l1, l2))))

Given your sample input, this outputs:

True

Demo: https://replit.com/@blhsing/PassionateUnwrittenSimulation

  • Related