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
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))]