I have a Python dictionary
steps = {1:"value1", 5:"value2", 2:"value3"}
I need to iterate over this sorted by key.
I tried this:
x = sorted(steps, key=lambda key: steps[key])
but the values are gone from x.
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 .
You can loop through a dictionary by using a for loop. When looping through a dictionary, the return value are the keys of the dictionary, but there are methods to return the values as well.
I need to iterate over this is sorted order by the key.
I think lambdas
is overkill here, try this:
>>> steps = {1:"val1", 5:"val2", 2:"val3"} >>> >>> for key in sorted(steps): ... print steps[key] ... val1 val3 val2
You need to iterate over steps.items()
, because an iteration over dict only returns its keys.
>>> x = sorted(steps.items()) >>> x [(1, 'value1'), (2, 'value3'), (5, 'value2')]
Iterate over sorted keys:
>>> for key in sorted(steps): ... # use steps[keys] to get the value
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