Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Sort dictionary with values closest to given value
>>> 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment