The data are kept in a list whose elements are dictionaries, where each dictionary contains the data for a single student: the student’s ID number, the subject’s name, as well as the number of points that he/she gained on each of the two partial exams, respectively. The format of each dictionary is the following:
{'ID' : _IDnumber_, 'subject' : _'Artificial Intelligence'_, 'Partial Exam 1' : _points1_, 'Partial Exam 2' : _points2_}
Now I need to define a function sum_partials()
, which receives a single argument – list of dictionaries containing student data (as described above), and returns the same list, but modified in such a way that each dictionary will contain only the total score (i.e. the sum of points) of the partial exams instead of the scores for the two partial exams.
Ex. result:
[{'ID': 12217, 'subject': 'Artificial Intelligence', 'Total score': 55}, {'ID': 13022, 'subject': 'Artificial Intelligence', 'Total score': 85}, {'ID': 13032, 'subject': 'Artificial Intelligence', 'Total score': 47}]
I have done it by using a function for editing each student which function I call as expression on a list comprehension:
def sum_partials(results):
# your code here
def update_student(student):
partial_exam1 = student['Partial Exam 1']
partial_exam2 = student['Partial Exam 2']
student.pop('Partial Exam 1')
student.pop('Partial Exam 2')
student['Total score'] = partial_exam1 + partial_exam2
return student
return [update_student(student) for student in results]
It works perfect, but I’m new to Python and I wonder if I can refactor my code!? Is there a solution for doing this in one row using only list comprehensions or maybe nested list comprehensions?
I mean, to do all the stuff I need to do without the update_student()
function but only by usinglist comprehensions
?
2
Answers
Keep in mind that while list comprehensions work, you might want to prioritize readable code rather than “this type of structure just because”.
Here, a simple
for
loop going through your list of students is just fine.Thanks @BoarGules for the compact one-liner calculation with
pop
.You can use the following listcomp: