Reputation: 1
Conditional statements in place of dictionary key
How can I reduce this code using dictionary i.e. how can I use conditional statement in place of key in dictionary such that if the condition is True return value as desired in image attached
Upvotes: 0
Views: 94
Reputation: 11342
You can create a dictionary with the ranges as the keys. Use list comprehension to get the correct value:
wt = 2345
drng = {(-1,0):0,(0,2000):25,(2000,4000):35,(7000,9e25):'OVERLOADED'}
x = [d[1] for d in drng.items() if d[0][0] < wt <= d[0][1]]
print(f'Time Required is {x[0]} minutes')
Output
Time Required is 35 minutes
Note that for the last entry, you will need to do a separate check to get the sentence correct. For now the sentence will be:
Time Required is OVERLOADED minutes
Upvotes: 1