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"
CodePudding user response:
If you want all the values where the age is in the interval you can use the following code:
def get_all_values(age):
res = []
for key, value in dict_interval .items():
if (age >= key[0] and age <= key[1]):
res.append(value)
return res
this function will return a list of all the correct values. If you can only get 1 correct value you can do it like that:
def get_value(age):
for key in dict_interval .keys():
if (age >= key[0] and age <= key[1]):
return dict_interval[key]
CodePudding user response:
def categorizer(value, dict_interval):
for k in dict_interval:
if k[0] < value < k[1]:
return(dict_interval[k])
This should work, assuming that key is unique I guess.