I need to sort a Python dictionary by keys, when keys开发者_StackOverflow中文版 are floating point numbers in scientific format.
Example:
a={'1.12e+3':1,'1.10e+3':5,'1.19e+3':7,...}
I need to maintain key-value links unchanged.
What is the simplest way to do this?Probably by simply converting back to a number:
sorted(a, key = lambda x: float(x))
['1.10e+3', '1.12e+3', '1.19e+3']
This just gives you a sorted copy of the keys. I'm not sure if you can write to a dictionary and change its list of keys (the list returned by keys()
on the dictionary) in-place. Sounds a bit evil.
You can sort the (key, value)
pairs by the float value
a={'1.12e+3':1,'1.10e+3':5,'1.19e+3':7,...}
print sorted(a.iteritems(), key=lambda (x,y):float(x))
# [('1.10e+3', 5), ('1.12e+3', 1), ('1.19e+3', 7)]
I guess you want floats anyways eventually so you can just convert them right away:
print sorted((float(x),y) for x,y in a.iteritems())
# [(1100.0, 5), (1120.0, 1), (1190.0, 7)]
精彩评论