Is it legitimate to delete items from a dictionary in Python while iterating over it?
For example:
for k, v in mydict.iteritems():
if k == val:
There is a way that may be suitable if the items you want to delete are always at the "beginning" of the dict iteration
while mydict:
key, value = next(iter(mydict.items()))
if should_delete(key, value):
del mydict[key]
else:
break
The "beginning" is only guaranteed to be consistent for certain Python versions/implementations. For example from What’s New In Python 3.7
the insertion-order preservation nature of dict objects has been declared to be an official part of the Python language spec.
This way avoids a copy of the dict that a lot of the other answers suggest, at least in Python 3.
I tried the above solutions in Python3 but this one seems to be the only one working for me when storing objects in a dict. Basically you make a copy of your dict() and iterate over that while deleting the entries in your original dictionary.
tmpDict = realDict.copy()
for key, value in tmpDict.items():
if value:
del(realDict[key])
You can't modify a collection while iterating it. That way lies madness - most notably, if you were allowed to delete and deleted the current item, the iterator would have to move on (+1) and the next call to next
would take you beyond that (+2), so you'd end up skipping one element (the one right behind the one you deleted). You have two options:
.keys()
et al for this (in Python 3, pass the resulting iterator to list
). Could be highly wasteful space-wise though.mydict
as usual, saving the keys to delete in a seperate collection to_delete
. When you're done iterating mydict
, delete all items in to_delete
from mydict
. Saves some (depending on how many keys are deleted and how many stay) space over the first approach, but also requires a few more lines.You could first build a list of keys to delete, and then iterate over that list deleting them.
dict = {'one' : 1, 'two' : 2, 'three' : 3, 'four' : 4}
delete = []
for k,v in dict.items():
if v%2 == 1:
delete.append(k)
for i in delete:
del dict[i]