Amanda
Amanda

Reputation: 2163

Comparing list of dictionaries when the keys are out of order

I have 2 lists of dictionaries.

a = [{"name": "hello", "city": "xyz"},{"city": "rty", "name": "ert"}]
b = [{"city": "xyz","name": "hello"},{"name": "ert", "city": "rty"}]

The above two lists are equal. But if I make a comparison using ==, it gives False. How could I check for equality between two lists of dictionaries when the keys could be out of order?

Upvotes: 2

Views: 3004

Answers (2)

kederrac
kederrac

Reputation: 17322

if you want to know if each list has the same dicts even the dict elements may not be on the same positions in the lists (as you mention un the comments) you can use:

a = [{"name": "hello", "city": "xyz"},{"city": "rty", "name": "ert"}]
b = [{"name": "ert", "city": "rty"}, {"city": "xyz","name": "hello"}]

print(a == b)
print(sorted(a, key=lambda d: sorted(d.items())) == sorted(b, key=lambda d: sorted(d.items())))

output:

False
True

Upvotes: 6

Kelly Bundy
Kelly Bundy

Reputation: 27650

I'm pretty sure you made a mistake somehow. I and others get True:

>>> a = [{"name": "hello", "city": "xyz"},{"city": "rty", "name": "ert"}]
>>> b = [{"city": "xyz","name": "hello"},{"name": "ert", "city": "rty"}]
>>> a == b
True

And that's what it should do.

The documentation about OrderedDict says (emphasis mine):

Equality tests between OrderedDict objects and other Mapping objects are order-insensitive like regular dictionaries.

And the documentation about Value comparisons says this, which is the case for those dicts:

Mappings (instances of dict) compare equal if and only if they have equal (key, value) pairs.

Upvotes: 1

Related Questions