Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a mapping of ranges into a dictionary

How can this be converted into a dictionary?

if grade>=96.5:return 5.83
elif grade>=92.5:return 5.5
elif grade>=89.5:return 5.16
elif grade>=86.5:return 4.83
elif grade>=82.5:return 4.5
elif grade>=79.5:return 4.16
elif grade>=76.5:return 3.83
elif grade>=72.5:return 3.5
elif grade>=69.5:return 3.16
elif grade>=68.5:return 2.83
elif grade>=64.5:return 2.5
else:return 0

I know how to make basic dictionaries, however, I am not sure whether it would look something like this:

grade_checker = {
    grade>96.5:5.83
}

Thanks!

like image 696
Daniel Avatar asked Nov 30 '22 21:11

Daniel


1 Answers

The short answer is that you should not convert this to a dictionary. This is best suited as a function, and it appears you are just missing your function definition, as I see you are using return in your code. Dictionaries are constructed from key-value pairs, and since your conditions involve >= evaluations, a dictionary is not appropriate. See the function implementation below:

def grade_checker(grade):

    if grade>=96.5: return 5.83
    elif grade>=92.5: return 5.5
    elif grade>=89.5: return 5.16
    elif grade>=86.5: return 4.83
    elif grade>=82.5: return 4.5
    elif grade>=79.5: return 4.16
    elif grade>=76.5: return 3.83
    elif grade>=72.5: return 3.5
    elif grade>=69.5: return 3.16
    elif grade>=68.5: return 2.83
    elif grade>=64.5: return 2.5
    else: return 0

grade_checker(75)
grade_checker(62)
grade_checker(94)

Returns:

3.5
0
5.5
like image 146
rahlf23 Avatar answered Dec 05 '22 12:12

rahlf23