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

DDD
Release: 2024-10-21 15:22:30
Original
972 people have browsed it

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())
Copy after login

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']
Copy after login

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!

source:php
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!