Fix Python – Order of keys in dictionaries in old versions of Python

Question

Asked By – rectangletangle

Code:

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

print l

This prints ['a', 'c', 'b']. I’m unsure of how the method keys() determines the order of the keywords within l. However, I’d like to be able to retrive the keywords in the “proper” order. The proper order of course would create the list ['a', 'b', 'c'].

Now we will see solution for issue: Order of keys in dictionaries in old versions of Python


Answer

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.

This question is answered By – Abhinav Gupta

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0