공부

[python] sort dict by key

승가비 2022. 9. 10. 10:48
728x90

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

https://stackoverflow.com/questions/16710112/python-iterate-over-dictionary-sorted-by-key

 

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: ste...

stackoverflow.com

 

728x90