"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > Why Did the Dictionary Ordering Behavior Change Between Python 2.7 and 3.3, and How Did It Evolve Later?

Why Did the Dictionary Ordering Behavior Change Between Python 2.7 and 3.3, and How Did It Evolve Later?

Published on 2024-11-02
Browse:219

Why Did the Dictionary Ordering Behavior Change Between Python 2.7 and 3.3, and How Did It Evolve Later?

Dictionary Ordering in Python 2.7 vs Python 3.3: Why the Change?

In Python 2.7, the ordering of dictionary keys was arbitrary yet consistent. However, this behavior changed in Python 3.3, where the ordering of keys obtained from methods like vars() appears non-deterministic.

This non-determinism stemmed from a security fix implemented in 2012, which was enabled by default in Python 3.3. The fix introduced hash randomization to prevent certain security vulnerabilities. As a result, the iteration order of dictionaries and sets became unpredictable.

In Python 3.6, a new implementation for the dict class was introduced that preserves insertion order. Consequently, as of Python 3.7, order-preserving behavior for dictionaries is now guaranteed.

Unexpected Consistency in Certain Use Cases

Despite the non-deterministic ordering, there are cases where a consistent order is maintained. For example:

list({str(i): i for i in range(10)}.keys())

In Python 2.7 and Python 3.6 (and later), this expression consistently produces the order:

['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']

This is because the counterexample uses a set comprehension, which creates an implicit ordered dictionary. In Python 3.3, however, the order may still vary due to the limitations in handling hash collisions.

Release Statement This article is reproduced at: 1729494555 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3