"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 Is Dictionary Ordering Non-Deterministic Post-Python 3.3?

Why Is Dictionary Ordering Non-Deterministic Post-Python 3.3?

Published on 2024-11-10
Browse:398

Why Is Dictionary Ordering Non-Deterministic Post-Python 3.3?

Why is Dictionary Ordering Non-Deterministic in Python 3.3?

In Python versions prior to 3.3, the ordering of dictionary keys was arbitrary but consistent. However, in Python 3.3, this ordering became non-deterministic.

This change results from a security fix implemented in 2012 and enabled by default in Python 3.3. Hash randomization, introduced to address security vulnerabilities, causes the iteration order of dictionaries and sets to be unpredictable and to differ across Python runs.

To disable hash randomization, you can set the PYTHONHASHSEED environment variable to 0.

Counterintuitive Example

While the counterexample in the question does not consistently yield the same result in Python 3.3, its limited number of different orderings stems from the handling of hash collisions.

This limitation is no longer present in Python 3.6 and later versions, where the insertion order of dictionaries is always preserved.

Release Statement This article is reprinted at: 1729494257 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