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:
<
This could work as a compromise between the two examples - two lines longer than the second one, but shorter and slightly faster than the first. Python 2:
dict_ = {k : random.randint(0, 40000) for k in range(0,200000)}
dict_remove = [k for k,v in dict_.iteritems() if v < 3000]
for k in dict_remove:
del dict_[k]
Split into a function and it's down to one line each call (whether this is more readable or not is your call):
def dict_remove(dict_, keys):
for k in keys:
del dict_[k]
dict_remove(dict_, [k for k,v in dict_.iteritems() if v < 3000])
Regardless of where the code is stored, you'll have to store the keys needing deletion somewhere. The only way around that is using generator expressions, which will explode the moment you delete a key for the first time.