Home > Article > Backend Development > How did Python handle dictionary key order in versions before 3.7?
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.
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.
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.
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!