0

I want to remove key from dictionary, but the one user enters, I have written this code, but it gives me this Error: for i in phoneNumbers.keys(): RuntimeError: dictionary changed size during iteration


phoneNumbers = {'John': '534-7887', 'Steven': '988-1187', "Max" : "765-2334", "Matt" : "987-1222"}
remove = input("Which key do you want to remove? ")
for i in phoneNumbers.keys():
    if i == remove:
        del phoneNumbers[remove]
print(phoneNumbers)

I know this one is correct, but why cant i remove it while I'm looping.

phoneNumbers = {'John': '534-7887', 'Steven': '988-1187', "Max" : "765-2334", "Matt" : "987-1222"}
remove = input("Which key do you want to remove? ")
del phoneNumbers[remove]
print(phoneNumbers)

  • 1
    Hi, and welcome to dba.se! This is a Python programming question and nothing to do with databases. I'm recommending this be closed - you can ask on StackOverflow. Feel free to come back when you do have a db question! – Vérace Dec 30 '22 at 11:16

1 Answers1

0

As the error message suggested avoid iterate and change size of the same object, it could give raise to side effects. Instead iterate over a shallow copy

for i in phoneNumbers.copy():
    if i == remove:
        del phoneNumbers[remove]
print(phoneNumbers)
cards
  • 3,936
  • 1
  • 7
  • 25