Skip to content

Instantly share code, notes, and snippets.

@aarshtalati
Last active July 2, 2016 02:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aarshtalati/f1f0dbaf3f96ee0fb4ed4da0d86cfc6f to your computer and use it in GitHub Desktop.
Save aarshtalati/f1f0dbaf3f96ee0fb4ed4da0d86cfc6f to your computer and use it in GitHub Desktop.
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