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 3.x and 2.x you can use use
list
to force a copy of the keys to be made:In Python 2.x calling
keys
made a copy of the keys that you could iterate over while modifying thedict
:But note that in Python 3.x this second method doesn’t help with your error because
keys
returns an a view object instead of copynig the keys into a list.