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

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

    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]
    

提交回复
热议问题