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

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

    Rather than using OrderedDict and bisect, consider the SortedDict type in the sortedcontainers module. It's a pure-Python and fast-as-C implementation of sorted list, sorted dict, and sorted set types with 100% testing coverage and hours of stress.

    With a SortedDict you can bisect for the desired key. For example:

    from itertools import islice
    from sortedcontainers import SortedDict
    
    def closest(sorted_dict, key):
        "Return closest key in `sorted_dict` to given `key`."
        assert len(sorted_dict) > 0
        keys = list(islice(sorted_dict.irange(minimum=key), 1))
        keys.extend(islice(sorted_dict.irange(maximum=key, reverse=True), 1))
        return min(keys, key=lambda k: abs(key - k))
    

    The closest function uses SortedDict.irange to create an iterator of keys nearest the given key. The keys are bisected with log(N) runtime complexity.

    >>> sd = SortedDict({-3: 'a', 0: 'b', 2: 'c'})
    >>> for num in range(-5, 5):
    ...     key = closest(sd, num)
    ...     print('Given', num, ', closest:', key)
    Given -5 , closest: -3
    Given -4 , closest: -3
    Given -3 , closest: -3
    Given -2 , closest: -3
    Given -1 , closest: 0
    Given 0 , closest: 0
    Given 1 , closest: 2
    Given 2 , closest: 2
    Given 3 , closest: 2
    Given 4 , closest: 2
    

    It's Pythonic to use PyPI!

提交回复
热议问题