I want to delete some items in a dictionary in a for loop, then I follow the codes from this How to delete items from a dictionary while iterating over it?
Looping over .keys
:
b = {'a':1, 'b' : 2}
for k in b.keys():
if b[k] == 1:
del b[k]
Results in:
Traceback (most recent call last):
File "<input>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
b
{'b': 2}
Similarly, looping over .items()
:
b = {'a':1, 'b' : 2}
for k, v in b.items():
if v == 1:
del b[k]
Traceback (most recent call last):
File "<input>", line 1, in <module>
RuntimeError: dictionary changed size during iteration
b
{'b': 2}
After the loop, it returns the correct result, but RuntimeError
is also raised, how can I fix it?