Home  >  Article  >  Backend Development  >  How did Python handle dictionary key order in versions before 3.7?

How did Python handle dictionary key order in versions before 3.7?

Barbara Streisand
Barbara StreisandOriginal
2024-11-11 17:48:02888browse

How did Python handle dictionary key order in versions before 3.7?

Order of Keys in Dictionaries in Previous Python Versions

When retrieving the keys of a dictionary using the keys() method in Python versions prior to 3.7, the order of the keys in the returned list may appear arbitrary. This unpredictability stems from how Python handled dictionaries in earlier versions.

Python 3.7

Starting with Python 3.7, dictionaries maintain insertion order by default. This means that the keys in the keys() output list will match the order in which they were inserted into the dictionary.

Python 3.6 (CPython)

In Python 3.6 (specifically the CPython implementation), dictionaries also default to insertion order preservation. However, this is considered an implementation detail, and its reliability across different Python implementations is not guaranteed.

Python >=2.7 and <3.6

For versions of Python between 2.7 and 3.6, the order of keys in the keys() list is determined by a hash function. This hash function is not guaranteed to be stable, so the order of keys may vary between executions, even with the same input data.

To ensure insertion order in these earlier versions of Python, you should use the collections.OrderedDict class. This class guarantees that the keys will be retrieved in the order they were inserted:

import collections

d = collections.OrderedDict({'a': 0, 'b': 1, 'c': 2})
l = d.keys()

print(l)  # Output: ['a', 'b', 'c']

The above is the detailed content of How did Python handle dictionary key order in versions before 3.7?. 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