cardinal_pythonlib.betweendict


Original code copyright (C) 2009-2022 Rudolf Cardinal (rudolf@pobox.com).

This file is part of cardinal_pythonlib.

Licensed under the Apache License, Version 2.0 (the “License”); you may not use this file except in compliance with the License. You may obtain a copy of the License at

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an “AS IS” BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.


Implements BetweenDict.*

class cardinal_pythonlib.betweendict.BetweenDict(d: Dict | None = None)[source]

Range dictionary for comparisons.

  • Create it with keys that are tuples/lists of length 2, such as (lower, upper), and values that are the values that this particular range should be mapped to.

  • Access it using a specific test value as the key, and the result will be the value for an appropriate range (or KeyError will be raised if none of the ranges contain the test value).

  • The test is lower <= testvalue < upper, i.e. ranges of [lower, upper).

Example:

bd = BetweenDict({
    # tests a <= x < b
    (100, float("inf")): "very high",  # from Python 3.5, can use math.inf
    (75, 100): "high",
    (50, 75): "medium",
    (25, 50): "low",
    (0, 25): "very low",
})

bd[500]  # 'very high'
bd[80]  # 'high'
bd[50]  # 'medium'
bd[-5]  # raises KeyError

Various implementation alternatives: