The order of keys in dictionaries
Python 3.7+
In Python 3.7.0 the insertion-order preservation nature of dict
objects has been declared to be an official part of the Python language spec. Therefore, you can depend on it.
Python 3.6 (CPython)
As of Python 3.6, for the CPython implementation of Python, dictionaries maintain insertion order by default. This is considered an implementation detail though; you should still use collections.OrderedDict
if you want insertion ordering that's guaranteed across other implementations of Python.
Python >=2.7 and <3.6
Use the collections.OrderedDict
class when you need a dict
that
remembers the order of items inserted.
You could use OrderedDict (requires Python 2.7) or higher.
Also, note that OrderedDict({'a': 1, 'b':2, 'c':3})
won't work since the dict
you create with {...}
has already forgotten the order of the elements. Instead, you want to use OrderedDict([('a', 1), ('b', 2), ('c', 3)])
.
As mentioned in the documentation, for versions lower than Python 2.7, you can use this recipe.
>>> print sorted(d.keys())
['a', 'b', 'c']
Use the sorted function, which sorts the iterable passed in.
The .keys()
method returns the keys in an arbitrary order.