I have a data in form a dictionary..
NOw I take the input from the user and it can be anything..
And I am trying to do the following.
If the key exists then cool.. fetch the value from the dictionary.
if not, then fetch the nearest (in numeric sense).
For example..if the input key is 200
and the keys are like :....
197,202,208...
Then probably 202 is the closest key to 200..
Now, from algorithm point of view. its straight forward.. but is there a pythonic way to do this?
Thanks
解决方案
here's your function on one line:
data.get(num, data[min(data.keys(), key=lambda k: abs(k-num))])
edit: to not evaluate the min when the key is in the dict use:
data[num] if num in data else data[min(data.keys(), key=lambda k: abs(k-num))]
or if all values in data evaluate to True you can use:
data.get(num) or data[min(data.keys(), key=lambda k: abs(k-num))]