Hello.
Given a dictionary
{'2.3': ['0', '1'], '4.9': ['0', '1'], '4.7': ['0', '1'], '3.5': ['0', '1'], '2.4': ['0', '1'], '3.17' : ['0', '1'], '4.8': ['0', '1'], '3.6': ['0']}
It is necessary to sort it by keys in ascending order. I’m trying to do this:
for x in sorted (dict_list.keys (), key = lambda x: float (x [: len (x )-1])):
print (x)
It turns out
2.3, 2.4, 3.5, 3.6, 3.17, 4.9, 4.7, 4.8
In general, it clearly sorts something wrong. Can you please tell me how to sort in ascending order of keys? Thanks in advance.
Answer 1, authority 100%
If you want to return a sorted list of keys / values, you can simply sort the dictionary by its keys:
for k in sorted (dict_list.keys ()):
print (k, ':', dict_list [k])
If you need to store sorted key / value pairs, try using OrderedDict
from collections import OrderedDict
# sort in ascending order of dictionary keys
OrderedDict (sorted (dict_list.items (), key = lambda t: t [0]))
UPD
at the request of the author, sorting in ascending order with the condition that 3.17 should be the last
for i in sorted (dict_list.items (), key = lambda x: (len (x [0]) , x [0])):
print (i [0])
If 3.17 should come first, you can simply add -
to the condition:
.. lambda x: (-len (x [0]), x [0]))