Objective: I have a dictionary, and a float value. I would like to sort the dictionary in such a way that, first key-value pair’s value is nearest (min absolute difference) to a given float value, and last would be the farthest (max absolute difference)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> chooseFrom | |
{'1': 10.3438090737, '3': 7.73275047259, '2': 12.9046550095, '5': 10.3438090737, '4': 12.9046550095, '7': 7.88437303088, '6': 5.12169187146, '8': 0.0} | |
>>> gh | |
7.73275047259 | |
# reference : http://stackoverflow.com/a/12141207/799593 | |
>>> test = sorted(chooseFrom, key=lambda x:abs(chooseFrom[x]–gh)) | |
>>> test | |
['3', '7', '1', '5', '6', '2', '4', '8'] | |
>>> for x in test: | |
… print '{} : {} ==> {}'.format(x, chooseFrom[x], abs(gh–chooseFrom[x])) | |
… | |
3 : 7.73275047259 ==> 0.0 | |
7 : 7.88437303088 ==> 0.15162255829 | |
1 : 10.3438090737 ==> 2.61105860111 | |
5 : 10.3438090737 ==> 2.61105860111 | |
6 : 5.12169187146 ==> 2.61105860113 | |
2 : 12.9046550095 ==> 5.17190453691 | |
4 : 12.9046550095 ==> 5.17190453691 | |
8 : 0.0 ==> 7.73275047259 |