Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 807
user984003 Avatar asked May 23 '13 09:05

user984003


People also ask

How do you iterate over 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 loop through a dictionary python?

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.


2 Answers

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 
like image 88
Dmitry Zagorulkin Avatar answered Sep 24 '22 20:09

Dmitry Zagorulkin


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 
like image 25
Ashwini Chaudhary Avatar answered Sep 24 '22 20:09

Ashwini Chaudhary