I am trying to delete a key from a dictionary while iterating through it. While directly trying to remove the key form the dictionary I was getting RuntimeError: dictionary changed size during iteration
. My code for that is.
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.