how to do I call a list from a dictionary to a function?

144
1
07-25-2019 12:24 PM
TaylorPampinella1
New Contributor

I have been taking an online python course and figured I'd try to create a grade calculator to apply what I have learned so far. I got my calculator to work, but I am stuck on one part. 

I want to call the "exams" list seen in bold to the def get_average function. I want to replace the bolded part of the function to something that calls the "exams" list and does the same thing as the current bolded portion of the function.

I guess the question is how to do I call a list from a dictionary to a function?

tay = {
"name": "Taylor",
"attendance": [100.0, 0.0, 100.0, 100.0, 0.0, 100.0, 100.0, 100.0, 100.0, 100.0],
"labs": [75.0, 80.0, 95.0, 95.0, 100.0],
"exams": [84.0, 88.0, 91.0, 95.0], 
}
#if you know anyway to make this a shorter script please let me know... call in list "exams"?
#I would also like to dump grades and weights of grades into a text file and call them into the script... not top priority though.

def average(numbers):
total = sum(numbers)
total = float(total)
return total/len(numbers)

def get_average(student):
attendance = average(student["attendance"])
labs = average(student["labs"])
return 0.05 * attendance + 0.15 * labs + 0.20 * tay["exams"][0] + 0.20 * tay["exams"][1] + 0.20 * tay["exams"][2] + 0.20 * tay["exams"][3]

 

def get_letter_grade(score):
if score >= 90:
return "A "
elif score >=80:
return "B"
elif score >=70:
return "C"
elif score >=60:
return "D"
else:
return "F"

print get_letter_grade(get_average(tay))

0 Kudos
1 Reply
JoshuaBixby
MVP Esteemed Contributor

Calculating an average of a list is simple enough, I would just do it inline and not create an extra def.  Also, if you are using Python 3, then you can use the mean function to calculate the average.

In terms of mapping scores to grades, the Python documentation already has a great example using bisect:  8.5. bisect — Array bisection algorithm — Python 2.7.16 documentation 

from bisect import bisect
from statistics import mean # only if using Python 3

def get_average(student):
    attendance = sum(student["attendance"]) / float(len(student["attendance"])) # or mean(student["attendence"]) if Python 3
    labs = sum(student["labs"]) / float(len(student["labs"])) # or mean(student["labs"]) if Python 3
    score = 0.05 * attendance
    score += 0.15 * labs
    score += sum(0.8/len(student["exams"]) * e for e in student["exams"]) # allow variable number of exams, not just 4
    return score

def get_letter_grade(score):
    breakpoints=[60, 70, 80, 90]
    grades='FDCBA'
    i = bisect(breakpoints, score)
    return grades[i]