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.
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 .
The straight answer is NO. You can not have duplicate keys in a dictionary in Python.
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.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With