Iterate through Python dictionary by Keys in sorted order

Question:

I have a dictionary in Python that looks like this:

D = {1:'a', 5:'b', 2:'a', 7:'a'}

The values of the keys are mostly irrelevant. Is there are way to iterate through the dictionary by keys in numerical order? The keys are all integers.

Instead of saying

for key in D:
    # some code...

Can I go through the dictionary keys in the order 1, 2, 5, 7?

Additionally, I cannot use the sort/sorted functions.

Asked By: ben

||

Answers:

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]
Answered By: Rohit Jain

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).

Answered By: isedev

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.

Answered By: kindall

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]
Answered By: JCash
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.