RuntimeError: dictionary changed size during iteration

students = {
    "sarah" : {
        "name" : "Sarah",
        "absences" : 0,
        "course_note" : 0,
        "group_note" : 0},
    "peter" : {
        "name" : "Peter",
        "absences" : 0,
        "course_note" : 0,
        "group_note" : 0
    }
}

def del_student(dictionary, value):
    for item in dictionary:
        for subItem in dictionary[item]:
            if value == dictionary[item][subItem]:
                del dictionary[item][subItem]
    return dictionary

val = input("Entry: ")
print(del_student(students,val))

When I execute this code, It displays this error. How to solve that ?

What it is saying is that you can’t delete an item in a dictionary while it is still looping through the dictionary. This messes up the keys, forcing it to restart the loop, etc.

I’d try something like this:

def del_student(dictionary, value):
    index1  = "" #known as "item" in the loop
    index2 = "" #known as "subItem" in the loop
    for item in dictionary:
        for subItem in dictionary[item]:
            if value == dictionary[item][subItem]:
                index1 = item
                index2 = subItem #this is where it gets tricky... I'm trying to set variables to remember the position of the object so that it can delete the item outside of the loop
                break #ends the for loop to stop searching through the array
        if index1 != "":
            break # If we found the student, break the loop
    if index1 == "": # If student not found
        raise Exception('Attempt to delete nonexistent student "' + value +  '" from dictionary') #throw an error
    else:
        del dictionary[index1][index2]

Please forgive me if my syntax is wrong. I haven’t used python in a while.

Let me know if this doesn’t work! Good luck!