UPDATED based on Lennart Regebro\'s answer
Suppose you iterate through a dictionary, and sometimes need to delete an element. The following is very efficient:
<
You can accomplish this by iterating over a static list of the key/value pairs of the dictionary, instead of iterating over a dictionary view.
Basically, iterating over list(dict_.items())
instead of dict_.items()
will work:
for k, v in list(dict_.items()):
if condition(k, v):
del dict_[k]
continue
# do other things you need to do in this loop
Here is an example (ideone):
dict_ = {0: 'a', 1: 'b', 2: 'c', 3: 'd', 4: 'e', 5: 'f', 6: 'g'}
for k, v in list(dict_.items()):
if k % 2 == 0:
print("Deleting ", (k, v))
del dict_[k]
continue
print("Processing", (k, v))
and the output:
Deleting (0, 'a')
Processing (1, 'b')
Deleting (2, 'c')
Processing (3, 'd')
Deleting (4, 'e')
Processing (5, 'f')
Deleting (6, 'g')