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.
The above is the detailed content of Why Is Dictionary Ordering Non-Deterministic Post-Python 3.3?. For more information, please follow other related articles on the PHP Chinese website!