Filter dict to contain only certain keys? Filter dict to contain only certain keys? python python

Filter dict to contain only certain keys?


Constructing a new dict:

dict_you_want = { your_key: old_dict[your_key] for your_key in your_keys }

Uses dictionary comprehension.

If you use a version which lacks them (ie Python 2.6 and earlier), make it dict((your_key, old_dict[your_key]) for ...). It's the same, though uglier.

Note that this, unlike jnnnnn's version, has stable performance (depends only on number of your_keys) for old_dicts of any size. Both in terms of speed and memory. Since this is a generator expression, it processes one item at a time, and it doesn't looks through all items of old_dict.

Removing everything in-place:

unwanted = set(keys) - set(your_dict)for unwanted_key in unwanted: del your_dict[unwanted_key]


Slightly more elegant dict comprehension:

foodict = {k: v for k, v in mydict.items() if k.startswith('foo')}


Here's an example in python 2.6:

>>> a = {1:1, 2:2, 3:3}>>> dict((key,value) for key, value in a.iteritems() if key == 1){1: 1}

The filtering part is the if statement.

This method is slower than delnan's answer if you only want to select a few of very many keys.