Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Python dict.keys() equality, order irrelevant

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading