I have checked all of the other questions with the same error yet found no helpful solution =/
I have a dictionary of lists:
d = {'a': [1], 'b': [1, 2], 'c': [], 'd':[]}
in which some of the values are empty. At the end of creating these lists, I want to remove these empty lists before returning my dictionary. Current I am attempting to do this as follows:
for i in d:
if not d[i]:
d.pop(i)
however, this is giving me the runtime error. I am aware that you cannot add/remove elements in a dictionary while iterating through it...what would be a way around this then?
In Python 2.x calling keys
makes a copy of the key that you can iterate over while modifying the dict
:
for i in d.keys():
Note that this doesn't work in Python 3.x because keys
returns an iterator instead of a list.
Another way is to use list
to force a copy of the keys to be made. This one also works in Python 3.x:
for i in list(d):
I believe you meant 'calling
keys
makes a copy of the keys that you can iterate over' aka theplural
keys right? Otherwise how can one iterate over a single key? I'm not nit picking by the way, am genuinely interested to know if that is indeed key or keysOr tuple instead of list as it is faster.
To clarify the behavior of python 3.x, d.keys() returns an iterable (not an iterator) which means that it's a view on the dictionary's keys directly. Using
for i in d.keys()
does actually work in python 3.x in general, but because it is iterating over an iterable view of the dictionary's keys, callingd.pop()
during the loop leads to the same error as you found.for i in list(d)
emulates the slightly inefficient python 2 behavior of copying the keys to a list before iterating, for special circumstances like yours.