2

This seems like it should be a rather simple thing to do but I've been unable to do it. Say I have a dictionary like:

d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}

I want to access the keys in the same order they are stored in the dictionary. I would have expected this to work:

print d.keys()[0]
banana

but the actual result is:

orange

Apparently this is because dictionaries are unordered in python. I've tried using collections.OrderedDict:

from collections import OrderedDict as odict
d = {'banana': 3, 'apple':4, 'pear': 1, 'orange': 2}
print odict(d).keys()

but the results are the same.

How can I do this? Giving the apparent complexity of performing this task, should I not be doing it this way? How else could I access the keys in a dictionary in order?

Community
  • 1
  • 1
Gabriel
  • 40,504
  • 73
  • 230
  • 404
  • You are getting the keys in the order they are stored in the dictionary. That order just differs from what you expected. The keys are not necessarily stored in the same as the order in which you *specified* the dictionary. – Martijn Pieters Oct 15 '14 at 12:55

2 Answers2

5

The source should not be a dictionary. Use other sequences that guarantee order (list, tuple, ..):

>>> from collections import OrderedDict as odict
>>> d = [('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2)]
>>> print odict(d).keys()
['banana', 'apple', 'pear', 'orange']
falsetru
  • 357,413
  • 63
  • 732
  • 636
3

When you tried OrderedDict, you still are including the construction of a regular dict (which, internally, during contruction, may be ordered differently than it is typed in the code, and will thus cause the constructed OrderedDict to also be ordered differently).

If you add the items sequentially, rather than "all at once via an unordered dict" then OrderedDict will work as you expect.

from collections import OrderedDict
d = OrderedDict()

d['banana'] = 3
d['apple'] = 4
d['pear'] = 1
d['orange'] = 2

print d.keys()

or from a sequential data type to begin with (if you really want dict-like behavior):

In [127]: d = OrderedDict([('banana',3), ('apple',4), ('pear',1), ('orange',2)])

In [128]: d
Out[128]: OrderedDict([('banana', 3), ('apple', 4), ('pear', 1), ('orange', 2)])

In [129]: d.keys()
Out[129]: ['banana', 'apple', 'pear', 'orange']
ely
  • 74,674
  • 34
  • 147
  • 228