简体   繁体   中英

Python, how to sort dictionary by keys, when keys are floating point numbers in scientific format?

I need to sort a Python dictionary by keys, when keys 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)]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM