Dictionaries are not sorted by key
suggest changeYou might expect a Python dictionary to be sorted by keys like, for example, a C++ std::map, but this is not the case:
myDict = {'first': 1, 'second': 2, 'third': 3}
print(myDict)
# Out: {'first': 1, 'second': 2, 'third': 3}
print([k for k in myDict])
# Out: ['first', 'second', 'third']
Python doesn’t have any built-in class that automatically sorts its elements by key. Since Python 3.7, a dict does preserve insertion order. The order above is the order the keys were inserted, and the same display was not guaranteed before CPython 3.6.
A normal dict is enough when you only need insertion order. collections.OrderedDict also remembers that order:
from collections import OrderedDict
oDict = OrderedDict([('first', 1), ('second', 2), ('third', 3)])
print([k for k in oDict])
# Out: ['first', 'second', 'third']
Keep in mind that initializing an OrderedDict with a standard dictionary does not sort the keys. It keeps the insertion order that dictionary already has.
The implementation of dictionaries was changed in Python 3.6 to improve their memory consumption. A side effect of this new implementation is that it also preserves the order of keyword arguments passed to a function:
def func(**kw): print(kw.keys())
func(a=1, b=2, c=3, d=4, e=5)
# dict_keys(['a', 'b', 'c', 'd', 'e'])
CPython 3.6 preserved this order as a side effect, and the 3.6 docs called that an implementation detail. Since Python 3.7 the insertion order of a dict, including keyword arguments, is part of the language.