pythondictionaryfilter

Fastest way of deleting certain keys from dict in Python


I'm looking for most fastest/effective way of deleting certain keys in a python dict

Here are some options

for k in somedict.keys(): 
    if k.startswith("someprefix"): 
        del somedict[k]

or

dict((k, v) for (k, v) in somedict.iteritems() if not k.startswith('someprefix'))

Logically first snippet should be faster on smaller dicts, it doesn't create a copy of a dict but creates a list of all keys, however double lookups and dict rebuilding is time consuming. While the second is faster on bigger dicts, but requires 2x more memory. I've checked my assumption in some small benchmark.

Anything faster?


Solution

  • If the dict is large enough, it may make sense to generate a whole new dict instead.

    dict((k, v) for (k, v) in somedict.iteritems() if not k.startswith('someprefix'))