35

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.

double-beep
  • 5,031
  • 17
  • 33
  • 41
ben
  • 665
  • 4
  • 10
  • 16

4 Answers4

45

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

isedev
  • 18,848
  • 3
  • 60
  • 59
  • 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 Feb 13 '13 at 21:35
  • One last thing. Do you know of any other ways to sort through the keys? I really appreciate your help. – ben Feb 13 '13 at 21:51
  • 10
    Asking for not sorted... then accept sorted :/ – Roberto Jul 09 '13 at 14:54
  • 1
    such is life ;) – isedev Nov 16 '16 at 01:56
  • 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++. – jlh Jan 27 '19 at 12:31
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.

kindall
  • 178,883
  • 35
  • 278
  • 309
6

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]
JCash
  • 312
  • 1
  • 3
  • 10
  • 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')]) – Peter Graham Jun 19 '15 at 17:52
2

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]
Rohit Jain
  • 209,639
  • 45
  • 409
  • 525
  • 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 Feb 13 '13 at 21:36
  • @ben. Then you would have to write your own sorting logic. But why would you want to re-invent the wheel? – Rohit Jain Feb 13 '13 at 21:37
  • Usually because someone is using stack overflow for his CS homework. – Tim Bird Sep 26 '17 at 18:14