I'm working on a function that takes a list of dictionaries as well as a desired year as input. The function will check if the desired year (key) exists if it does it will calculate the average of the GPA's for that key. If the desired year doesnt exist it will return none. I currently have the problem working for key's that do exists, but not sure how to return none/handle instances where key's dont exist. For senior it calculates the average correctly for all seniors, but not sure how to handle the 2nd function call where junior doesn't exist.
Output for senior is correct: 2.19
However it should return none for junior.
CodePudding user response:
Try this:
def avgGpa(studentDic, desiredYear):
res = [dct['GPA'] for dct in studentDic if dct['year'] == desiredYear]
if res:
return sum(res) / len(res)
return None
print(avgGpa(student_data, 'senior'))
print(avgGpa(student_data, 'junior'))
Output:
2.19
None
CodePudding user response:
Move avg
calculation out of loop (no need to calculate for each iteration) and check if year
is empty, if it is empty return None:
def avgGpa(studentDic, desiredYear):
year = []
for value in studentDic:
if value['year'] == desiredYear:
year.append(value)
if len(year) == 0:
return None
avg = sum(value['GPA'] for value in year) / len(year)
return avg
CodePudding user response:
Another solution, using statistics.mean
:
from statistics import mean, StatisticsError
student_data = [
{"id": 0, "year": "freshman", "GPA": 0.03},
{"id": 1, "year": "senior", "GPA": 0.7},
{"id": 2, "year": "senior", "GPA": 2.77},
{"id": 3, "year": "sophomore", "GPA": 1.1},
{"id": 4, "year": "sophomore", "GPA": 1.05},
{"id": 5, "year": "freshman", "GPA": 0.43},
{"id": 6, "year": "senior", "GPA": 3.1},
]
def avgGpa(studentDic, desiredYear):
try:
return mean(d["GPA"] for d in studentDic if d["year"] == desiredYear)
except StatisticsError:
pass
print(avgGpa(student_data, "senior"))
print(avgGpa(student_data, "junior"))
Prints:
2.19
None