Нужно написать код, который вернет ключ по среднему из значений словаря
Описание кода: A get_excellent function that accepts dictionary as input. The names of students are keys, and the lists of grades are values (integers from 1 to 10). It is guaranteed that the dictionary contains information about at least one student. The function should return a list of names of students whose average score is at least 8, sorted alphabetically. If there are no such students, the function will return an empty list.
Пример:
Input:{
'Harry Potter': [7, 6, 8, 6, 6],
'Hermione Granger': [10, 10, 9, 10, 10, 9, 9],
'Ron Weasley': [6, 5, 7, 4, 5],
'Ginny Weasley': [9, 7, 8]
}
Output: ['Ginny Weasley', 'Hermione Granger']
Пробовала писать:
def get_excellent(dictionary):
if not dictionary:
return []
average_grade = sum(dictionary.values()) / len(dictionary.values())
eligible_students = [name for name, average_grade in dictionary.items() if average_grade >= 8]
return sorted(eligible_students)
Заранее спасибо!
Ответы (1 шт):
Вы что-то непонятное написали в своей функции - она у вас выполняется при условии if not dictionary, что странно. Вам надо пройтись по ключам, проверить среднее, вывести. делается вообще одной строкой:
d = {
'Harry Potter': [7, 6, 8, 6, 6],
'Hermione Granger': [10, 10, 9, 10, 10, 9, 9],
'Ron Weasley': [6, 5, 7, 4, 5],
'Ginny Weasley': [9, 7, 8]
}
def get_excellent(dictionary):
return sorted([x for x in dictionary if sum(dictionary[x])/len(dictionary[x])>=8])
print(get_excellent(d))
['Ginny Weasley', 'Hermione Granger']