Iterate through Python dictionary by Keys in sorted order

46,822

Solution 1

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

Solution 2

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.

Solution 3

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]

Solution 4

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]
Share:
46,822
ben
Author by

ben

Updated on February 01, 2020

Comments

  • ben
    ben about 4 years

    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.

  • ben
    ben about 11 years
    Is there a way to do this without using the sort function explicitly? This is part of a challenge where we have to sort through everything without using the sort function. Sorry I should have mentioned this earlier.
  • ben
    ben about 11 years
    Is there a way to do this without using the sort function explicitly? This is part of a challenge where we have to sort through everything without using the sort function. Sorry I should have mentioned this earlier.
  • Rohit Jain
    Rohit Jain about 11 years
    @ben. Then you would have to write your own sorting logic. But why would you want to re-invent the wheel?
  • Rohit Jain
    Rohit Jain about 11 years
    This is one clever hack. But really an overkill in case dictionary has only say 2 keys, 1 and 1000000?? what say?
  • kindall
    kindall about 11 years
    Yes, sorting is definitely better!
  • Rohit Jain
    Rohit Jain about 11 years
    Still this gives OP exactly what he wanted.
  • ben
    ben about 11 years
    One last thing. Do you know of any other ways to sort through the keys? I really appreciate your help.
  • Roberto
    Roberto almost 11 years
    Asking for not sorted... then accept sorted :/
  • Peter Graham
    Peter Graham almost 9 years
    If you'd rather not alter the existing dictionary, just make a temporary variable for your ordered dictionary and set it to OrderedDict(D) >>> from collections import OrderedDict >>> a = {'a': 'A', 'b': 'B', 'c': 'C'} >>> OrderedDict(a) returns -> OrderedDict([('a', 'A'), ('b', 'B'), ('c', 'C')])
  • isedev
    isedev over 7 years
    such is life ;)
  • Tim Bird
    Tim Bird over 6 years
    Usually because someone is using stack overflow for his CS homework.
  • jlh
    jlh over 5 years
    Come someone comment on the performance of this? What if such a loop needs to happen very often. Does sorted() re-sort it every time? Is there are way to always keep a dict sorted by key so that iterating it in key-order is efficient? Something like std::map in C++.