from the following dictionary with tuple
as keys and a string
as value:
JavaScript
x
2
1
dict_interval = {(1,5):"foo",(5,100):"bar"}
2
by using the dict, how would be possible to use a function with the following behaviour?
JavaScript
1
3
1
age = 4
2
categorizer(age, dict_interval)
3
gives the following output:
JavaScript
1
2
1
"foo"
2
Advertisement
Answer
If you expect age to be within multiple intervals and you want to get them all:
JavaScript
1
9
1
# Categoriser, returns a list
2
def categoriser(age, d) -> list:
3
return [value for key, value in d.items()
4
if is_between(age, key)]
5
6
# Helper function
7
def is_between(value, interval):
8
return interval[0] <= value < interval[1]
9
I have added an overlapping interval to your data
JavaScript
1
4
1
>>> dict_interval = {(1,5): "foo", (2, 5): "foo2", (5,100): "bar"}
2
>>> categoriser(4, dict_interval)
3
["foo", "foo2"]
4
If you want the first value only:
JavaScript
1
6
1
# Categoriser, returns first value
2
def categoriser(age, d) -> str:
3
for key, value in d.items():
4
if is_between(age, key):
5
return value
6
JavaScript
1
3
1
>>> categoriser(4, dict_interval)
2
"foo"
3