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:
del mydict[k]
The idea is to remove elements that don't meet a certain condition from the dictionary, instead of creating a new dictionary that's a subset of the one being iterated over.
Is this a good solution? Are there more elegant/efficient ways?
You could first build a list of keys to delete, and then iterate over that list deleting them.
You can use a dictionary comprehension.
d = {k:d[k] for k in d if d[k] != val}
With python3, iterate on dic.keys() will raise the dictionary size error. You can use this alternative way:
Tested with python3, it works fine and the Error "dictionary changed size during iteration" is not raised:
I use it when, from a dictionary using lot's of memory, I want to construct an other dictionary (containing modification of the first one) without doing "copy" and overload the RAM.
You could also do it in two steps:
My favorite approach is usually to just make a new dict:
It's cleanest to use
list(mydict)
:This corresponds to a parallel structure for lists:
Both work in python2 and python3.
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.