Ordering a key in a dict not guaranteed.
The documentation says:
Itβs best to think of the dictionary as an unordered set of key: value pairs that require unique keys (in one dictionary) ...
The keys() dictionary method returns a list of all the keys used in the dictionary in random order (if you want it to be sorted, just apply the sorted() function to it).
Python 2.7+ and 3.1+ have the OrderedDict class in collections as described by PEP 372 , which does exactly what you want. It remembers the order of adding keys:
>>> from collections import OrderedDict >>> od = OrderedDict() >>> od[1] = "one" >>> od[2] = "two" >>> od[3] = "three" >>> od.keys() [1, 2, 3]
source share