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

前端 未结 6 2152
渐次进展
渐次进展 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条回答
  •  萌比男神i
    2020-12-30 02:50

    This should do what you want (minus getting it from a key, but you can figure that out :).

    f = lambda a,l:min(l,key=lambda x:abs(x-a))
    numbers = (100, 200, 300, 400)
    num = int(raw_input())
    print 'closest match:', f(num, numbers)
    

    Note: f is from this question.

提交回复
热议问题