python: iterate over dictionary sorted by key

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.


Solution 1:

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

Solution 2:

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

Solution 3:

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.

Solution 4:

In case your keys are not integers, but strings that should be parsed as integers:

steps = {'1':'value1', '10': 'value0', '5':'value2', '2':'value3'}

you can use something similar to your solution:

for key in sorted(steps, key=lambda key: int(key)):
    print(key, steps[key])

1
2
5
10