Iterate through Python dictionary by Keys in sorted order

You can use this:

for key in sorted(D.iterkeys()):
    .. code ..

In Python 3.x, use D.keys() (which is the same as D.iterkeys() in Python 2.x).


Assuming that the keys/values are inserted in order, you can use an OrderedDict:

>>> from collections import OrderedDict
>>> d = OrderedDict()
>>> d[1] = 'a'
>>> d[2] = 'a'
>>> d[5] = 'b'
>>> d[7] = 'a'
>>> d
OrderedDict([(1, 'a'), (2, 'a'), (5, 'b'), (7, 'a')])
>>> d.keys()
[1, 2, 5, 7]

Taking into account your stipulation that you don't want to sort, and assuming the keys are all integers, you can simply find the maximum and minimum values of the keys, then iterate over that range and check whether each is actually in the dictionary.

for key in xrange(min(D), max(D) + 1):
    if key in D:
        print D[key]

This isn't very efficient, of course, but it will work, and it avoids sorting.


You can get the list of keys using dict.keys(), and then iterate over a sorted view of the list:

for key in sorted(D.keys()):
    print key, D[key]