Python: Find closest from given dictionary values


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)

>>> 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(ghchooseFrom[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

view raw
DictCustomSort.py
hosted with ❤ by GitHub

Leave a Comment

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s