On Sun, Apr 27, 2014 at 12:14 PM, Steven D'Aprano <steve+comp.lang.pyt...@pearwood.info> wrote: > I think the two obviously good enough approaches are: > > - save a "to be deleted" list, then delete those keys; > > - copy the "not to be deleted" items into a new dict
For a small enough dict that the performance question doesn't matter, I'd go with the other option: iterate over a snapshot of the keys. Compare: # Naive approach: for k in d: if f(k): del d[k] # Snapshot of keys: for k in list(d): if f(k): del d[k] No extra loop at the end, no switching out and in of contents, just one little change in the loop header. Obviously you don't want to do this when you're deleting two out of three billion, but for smallish dicts, that won't make a visible change. ChrisA -- https://mail.python.org/mailman/listinfo/python-list