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:
# code...
Can I go through the dictionary keys in the order 1, 2, 5, 7? Thanks for your help in advance.
Additionally, I cannot use the sort/sorted functions.
解决方案
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).