3

I am practising a really easy python code. I have tried to find the solution of it, but couldn't find it.

def del_contacts():
for name, number in d1.items():
    if (del_name == name):
        del d1.name and print ("Contact deleted!")
else:
    print ("Contact does not exist")

z = input ("Do you wish to delete any of the number you added? ")
if z == 'yes':
    del_name = input ("Type the name of the contact you wish to delete")
    del_contacts()
else:
    print ("ok")

but this gives me error in <module> del_contacts() followed with in del_contacts for name, numbers in d1.items(): RuntimeError: dictionary changed size during iteration

Have been facing such problem a lot. Can anyone please tell me WHY this error is happening? Any fix and what should I do in future to avoid such errors?

U. Patel
  • 33
  • 1
  • 1
  • 3

1 Answers1

13

You are modifying the dictionary while iterating over it. Just create a copy of the dict when getting the items

def del_contacts():
    for name, number in d1.copy().items():
        if (del_name == name):
            del d1.name and print ("Contact deleted!")
        else:
            print ("Contact does not exist")
Netwave
  • 40,134
  • 6
  • 50
  • 93