Python: find closest key in a dictionary from the given input key

前端 未结 6 2143
渐次进展
渐次进展 2020-12-30 02:25

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

6条回答
  •  攒了一身酷
    2020-12-30 02:46

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

提交回复
热议问题