2

I want to compute the overall grade of each student. Add the overall grade in a new dictionary called midterm_grades, with the students as keys, and the overall grades as (integer) values.

grades = {
    "studentA" : [5, 2, 3, 1, 2, 4, 5, 5, 1, 1],
    "studentB" : [1, 2, 5, 5, 2, 0, 1, 5, 5, 2],
    "studentC" : [2, 5, 5, 5, 5, 0, 1, 3, 1, 0],
    "studentD" : [0, 1, 0, 5, 2, 5, 1, 3, 3, 5],
    "studentE" : [5, 4, 5, 5, 1, 5, 1, 4, 4, 5],
    "studentF" : [2, 2, 1, 1, 1, 3, 1, 3, 0, 1],
    "studentG" : [5, 5, 5, 5, 5, 4, 3, 5, 3, 1],
}
dct_sum = {k: sum(v.values()) for k, v in grades.items()}

However, Python throw a error message: AttributeError: 'list' object has no attribute 'values'

2 Answers 2

3

The error couldn't be clearer. Each v is each list, so you were trying to get attribute that the lists don't have (.values()), so try to use only sum with each list:

dct_sum = {k: sum(v) for k, v in grades.items()}

Also, this is a good scenario to use toolz.dicttoolz.valmap:

from toolz.dicttoolz import valmap

dct_sum = valmap(sum,grades)

Both outputs:

dct_sum
{'studentA': 29,
 'studentB': 28,
 'studentC': 27,
 'studentD': 25,
 'studentE': 39,
 'studentF': 15,
 'studentG': 41}
Sign up to request clarification or add additional context in comments.

Comments

0

v is already the value list for the key k. Just sum that

>>> dct_sum = {k: sum(v) for k, v in grades.items()}
>>> dct_sum
{'studentA': 29, 'studentB': 28, 'studentC': 27, 'studentD': 25, 'studentE': 39, 'studentF': 15, 'studentG': 41}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.