Iterate through Python dictionary by Keys in sorted order
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]
ben
Updated on February 01, 2020Comments
-
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 about 11 yearsIs 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 about 11 yearsIs 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 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 about 11 yearsThis is one clever hack. But really an overkill in case dictionary has only say 2 keys,
1
and1000000
?? what say? -
kindall about 11 yearsYes, sorting is definitely better!
-
Rohit Jain about 11 yearsStill this gives OP exactly what he wanted.
-
ben about 11 yearsOne last thing. Do you know of any other ways to sort through the keys? I really appreciate your help.
-
Roberto almost 11 yearsAsking for not sorted... then accept sorted :/
-
Peter Graham almost 9 yearsIf 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 over 7 yearssuch is life ;)
-
Tim Bird over 6 yearsUsually because someone is using stack overflow for his CS homework.
-
jlh over 5 yearsCome 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 likestd::map
in C++.