How to use a range for dict keys?

后端 未结 2 1468
野趣味
野趣味 2021-01-23 17:19

I have a program that scans Google for links, it verifies how many links you\'ve found and then tries to find a success right for your search:

def check_urls_for         


        
2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-23 17:41

    RangeKeyDict class could be able to handle cases like this, which is more general and easy to use. For usage, check the codes in __main__

    to install it using:

    pip install range-key-dict
    

    Usage:

    from range_key_dict import RangeKeyDict
    
    if __name__ == '__main__':
        range_key_dict = RangeKeyDict({
            (0, 100): 'A',
            (100, 200): 'B',
            (200, 300): 'C',
        })
    
        # test normal case
        assert range_key_dict[70] == 'A'
        assert range_key_dict[170] == 'B'
        assert range_key_dict[270] == 'C'
    
        # test case when the number is float
        assert range_key_dict[70.5] == 'A'
    
        # test case not in the range, with default value
        assert range_key_dict.get(1000, 'D') == 'D'
    

    https://github.com/albertmenglongli/range-key-dict

    Reference: Please check the answer in this post: Range as dictionary key in Python

提交回复
热议问题