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

前端 未结 6 2068
渐次进展
渐次进展 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:32

    This issue is made a lot harder by dict keys being in no particular order. If you can play with how you make the dict so they are in order (like your example) and use python >= 2.7 you can use OrderedDict and bisect to make this lightning fast.

    import collections
    a = collections.OrderedDict()
    for i in range(100):
        a[i] = i
    
    import bisect
    ind = bisect.bisect_left(a.keys(), 45.3)
    

    Then you only have to check element ind and ind-1 to see which is closer, thus making a lot fewer calculations.


    As pointed out below by Steven G, in Python3 the .keys() is not just a list and must be changed into one.

    bisect.bisect_left(list(a.keys()), 45.3)
    

提交回复
热议问题