I am trying to delete a key from a dictionary while iterating through it. When removing the key from the dictionary I get:
RuntimeError: dictionary changed size during iteration
My code:
mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
for k, v in mydict.items():
if k == 'two':
del(mydict[k])
continue
print(k)
To avoid this I copied the same dictionary to another dictionary and then I tried to remove the content from the copied dictionary while iterating the previous dictionary. But still, I am getting the error.
mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
new_dict = mydict
for k, v in mydict.items():
if k == 'two':
del(new_dict[k])
continue
print(k)
So can anyone please help to solve this issue.
For Python-3-x the easy way is to convert the dict into a list() in the iteration:
mydict = {'one': 1, 'two': 2, 'three': 3, 'four': 4}
for k, v in list(mydict.items()):
if k == 'two':
del(mydict[k])
continue
print(k)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With