How to remove key from dictionary? (asking user which one) Python

55 Views Asked by At

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

There are 1 best solutions below

0
cards On

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)