8

I have the following structure for illustration:
list1 = [{'dict1':1}, {'dict2':2}] list2 = [{'dict2':2}, {'dict1':1}]

Now I as you see both lists are the same in content, but list1 == list2 produce False.

I have a test using pytest which one of its lines is:
assert list1 == list2

I want the ability to return True (content check), and if there are differences to show them them using pytest in a similar way it would be raised when doing something like:
assert 'hi1'=='hi2'

Any idea will be appreciated

JavaSa
  • 5,813
  • 16
  • 71
  • 121
  • 3
    From the linked answer, I'd use `sorted(list1) == sorted(list2)` - you can't use `set` on unhashable objects like dicts. Also `set` will return `true` for lists that contain different numbers of the same elements, eg `set([0, 1, 1, 2]) == set([0, 0, 1, 2])`. – Peter DeGlopper Sep 26 '17 at 22:07
  • 3
    Unfortunately, a list of dicts can't be sorted in Python 3: >>> sorted([{'a': '1'}, {'b': '2'}]) Traceback (most recent call last): File "", line 1, in TypeError: '<' not supported between instances of 'dict' and 'dict' which left me scratching my head a bit. Best I could manage is to assert the length of the list, then assert each dict in the 'check list' is also in the actual list; that should prove they're equivalent. – Adam Williamson Nov 28 '18 at 08:12
  • 6
    Not sure why this was closed as duplicate... none of the responses in the other thread deal with a list of dicts. You can use sorted as @PeterDeGlopper pointed out. In order for it to work, you need a `key` function. For example: `sorted([{'dict2': 1}, {'dict1': 2}], key=lambda x: sum(x.values()))`, which would take the sum of all the values for each dict (regardless of keys) and use that for sorting (this would only work if all values are numbers). As long as your function creates a unique order, it should work. – aiguofer Jun 07 '19 at 05:36
  • To add to the above - a robust (if slow) key function would be `lambda x: json.dumps(x, sort_keys=True)` – Stuart Moore Aug 05 '20 at 10:56

0 Answers0