Home >Backend Development >Python Tutorial >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?

DDD
DDDOriginal
2024-10-21 15:22:301068browse

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.

The above is the detailed content of Why Did the Dictionary Ordering Behavior Change Between Python 2.7 and 3.3, and How Did It Evolve Later?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn