. Advertisement .
..3..
. Advertisement .
..4..
For the “runtimeerror: dictionary changed size during iteration” problem. I tried to fix it, but It doesn’t work and returns the result I want. Here is my program:
d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]}
for i in d:
if not d[i]:
d.pop(i)
and
RuntimeError: dictionary changed size during iteration
has occurred. I’ve checked the entire command line but still can’t find the mistake.
The cause: The reason for this error is that while a dictionary changing during for loop, you can not iterate through it.
Solution: Let’s make a casting to list and iterate over that list as below:
Only
copy
is requiredYou can iterate over the dictionary fields and change the desired
d
on the fly. It works with every Python version so it’s easier to understand.(BTW) Generally, to iterate over the copy of your data structures, instead of
.copy
for dictionary or slicing[:]
for lists you can useimport copy
->copy.copy
(for shallow copies which are equivalent tocopy
that’s supported by dictionaries, or slicing[:]
that’s supported by lists) on your data structure.