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