Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Iterate through Python dictionary by Keys in sorted order [duplicate]

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.

like image 353
ben Avatar asked Feb 13 '13 21:02

ben


People also ask

How do you iterate through a dictionary order in Python?

A standard solution to iterate over a dictionary in sorted order of keys is using the dict. items() with sorted() function. To iterate in reverse order of keys, you can specify the reverse argument of the sorted() function as True .

Can you have duplicate keys in dictionary Python?

The straight answer is NO. You can not have duplicate keys in a dictionary in Python.

Can you iterate over dictionary keys?

To iterate through the dictionary's keys, utilise the keys() method that is supplied by the dictionary. An iterable of the keys available in the dictionary is returned. Then, as seen below, you can cycle through the keys using a for loop.

Does order of keys matter in dictionary Python?

Changed in Python 3.7 Dictionaries preserve insertion order. Note that updating a key does not affect the order. Keys added after deletion are inserted at the end. The Dictionary order is guaranteed to be insertion order.


1 Answers

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

like image 124
isedev Avatar answered Sep 19 '22 20:09

isedev