Search code examples
pythontuples

Dictionary with a list of tuples as values. How can I replace a tuple in the list with a new tuple using a function


Using a function add_course, I want to replace a tuple in a list with a new tuple if one of the values in the new tuple is greater than the corresponding value of the tuple that is currently in the list.

here is my code:

def add_student(students, name):
    if name not in students:
        # students.update(name:[])
        students[name] = []

def print_student(students, name):
    if name not in students:
        print(f"{name}: no such person in the database")
    elif len(students[name]) < 1:
        print(f"{name}:")
        print(" no completed courses")
        # 
    elif len(students[name]) > 0:
        print(f"{name}:")
        print(f" {len(students[name])} completed courses:")
        for course in students[name]:
            # print(f"{len(students[name])}  completed courses:")
            print(f"  {course[0]} {course[1]}")
        av_grade = 0
        for course in students[name]:
            av_grade += course[1]
        print(f" average grade {av_grade / len(students[name])}")

def add_course(students,name,course: tuple):
    if course[1] == 0:
        return 0
    elif course[0] in students[name]:
        temp = course
        if temp[1] < course[1]:
            return 0
        else:
            course = temp
    students[name].append(course)

if __name__ == "__main__":
    students = {}
    add_student(students, "Peter")
    add_course(students, "Peter", ("Introduction to Programming", 3))
    add_course(students, "Peter", ("Advanced Course in Programming", 2))
    add_course(students, "Peter", ("Data Structures and Algorithms", 0))
    add_course(students, "Peter", ("Introduction to Programming", 2))
    print_student(students, "Peter")

In the "main" code above you can see that "Peter" has taken the course "Introduction to Programming" twice, with his score listed as part of the tuple. If Peter's score is greater than the first time he took the course, I need to replace the lower scoring tuple with the higher. Conversely, if Peter's score is less than the first time he took the course I need to "not add" the completed course ("return 0" is my thought). I know my add_course function syntax is wrong but I'm hoping I'm on the right track?

output should be:

Peter:
 2 completed courses:
  Introduction to Programming 3
  Advanced Course in Programming 2
 average grade 2.5

my current output is:

Peter:
 3 completed courses:
  Introduction to Programming 3
  Introduction to Programming 2
  Advanced Course in Programming 2
 average grade 2.33

I have searched for hours for a solution but I'm not Python-savvy enough at this point to not ask for help.


Solution

  • Loop over the list, looking for the course name. If you find it, replace that element with the new tuple and return. If you don't find it, append the new tuple.

    def add_course(students,name,course: tuple):
        if name not in students:
            raise ValueError(f"{name}: no such person in the database")
        if course[1] == 0:
            return
        for i, (cname, cvalue) in enumerate(students[name]):
            if cname == course[0]: # course found, replace it if necessary
                if cvalue < course[1]:
                    students[name][i] = course
                return
    
        # course not found, add it
        students[name].append(course)