skip to Main Content

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


  1. 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.

    def sum_partials(list_of_students): 
        for student in list_of_students:
            student['Total score'] = student.pop('Partial Exam 1') + student.pop('Partial Exam 2')
    
        return list_of_students
    

    Thanks @BoarGules for the compact one-liner calculation with pop.

    Login or Signup to reply.
  2. You can use the following listcomp:

    lst = [{'ID': 12217, 'subject': 'Artificial Intelligence', 'Partial Exam 1' : 10, 'Partial Exam 2' : 20}]
    
    [{'ID': i['ID'], 'subject': i['subject'], 'Total score': i['Partial Exam 1'] + i['Partial Exam 2']} for i in lst]
    # [{'ID': 12217, 'subject': 'Artificial Intelligence', 'Total score': 30}]
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search