Home > Blockchain >  dict.keys() equality, order irrelevant
dict.keys() equality, order irrelevant

Time:06-28

Why do I get True why comparing dict.keys() when the keys are in different orders? I'm on windows cpython 3.10, which preserves insertion order since 3.6 , but I wonder if this result holds for earlier versions.

d1 = {1:2, 2:3, 3:4}
d2 = {3:5, 2:6, 1:7}

print(d1.keys() == d2.keys()) # True
print(list(d1.keys()) == list(d2.keys())) # False

CodePudding user response:

The docs for Dictionary view objects explain as follows:

Keys views are set-like since their entries are unique and hashable. If all values are hashable, so that (key, value) pairs are unique and hashable, then the items view is also set-like. (Values views are not treated as set-like since the entries are generally not unique.) For set-like views, all of the operations defined for the abstract base class collections.abc.Set are available (for example, ==, <, or ^).

So == will work just as if dict.keys() were a set.

CodePudding user response:

Dict keys may be retrieved in insertion order but its still a set, and sets should compare regardless of order. In fact, all set comparison operations work (and return python set when appropriate). It would be strange if d1 | d2 operated differently depending on insertion order. Equality is the same.

  • Related