python: iterate over dictionary sorted by key
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
You can also use one of Python's many SortedDict container types. These types automatically maintain the dictionary sorted in key-order. Take a look at the sortedcontainers module which is pure-Python and fast-as-C-implementations. There's a performance comparison that benchmarks several other implementations against each other.
In your case then, you'd use:
from sortedcontainers import SortedDict
steps = SortedDict({1:"value1", 5:"value2", 2:"value3"})
# Then iterate the items:
for key, value in steps.items():
print key, value
# Or iterate the values:
for value in steps.values():
print value
Iteration for keys/values/items works automatically by sorted key order.