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?