Search code examples
pythondictionaryintervals

check if numeric element is in an interval key dictionary in python


from the following dictionary with tuple as keys and a string as value:

dict_interval = {(1,5):"foo",(5,100):"bar"}

by using the dict, how would be possible to use a function with the following behaviour?

age = 4    
categorizer(age, dict_interval)

gives the following output:

"foo"

Solution

  • If you expect age to be within multiple intervals and you want to get them all:

    # Categoriser, returns a list
    def categoriser(age, d) -> list:
        return [value for key, value in d.items() 
                if is_between(age, key)]
    
    # Helper function
    def is_between(value, interval):
        return interval[0] <= value < interval[1]
    

    I have added an overlapping interval to your data

    >>> dict_interval = {(1,5): "foo", (2, 5): "foo2", (5,100): "bar"}
    >>> categoriser(4, dict_interval)
    ["foo", "foo2"]
    

    If you want the first value only:

    # Categoriser, returns first value 
    def categoriser(age, d) -> str:
        for key, value in d.items():
            if is_between(age, key):
                return value
    
    >>> categoriser(4, dict_interval)
    "foo"