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
Using sortedcontainers.SortedDict, you can do this like this:
def closest_item(sdict, key):
if len(sdict) == 0:
raise KeyError('No items in {sdict.__class__.__name__}')
if len(sdict) == 1:
return next(iter(sdict.items()))
idx_before = next(sdict.irange(minimum=key), None)
idx_after = next(sdict.irange(maximum=key, reverse=True), None)
if idx_before is None:
idx = idx_after
elif idx_after is None:
idx = idx_before
else:
idx = min(idx_before, idx_after, key=lambda x: abs(x - key))
return idx, sdict[idx]