HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCritical

Filter dict to contain only certain keys?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
keyscontainonlyfilterdictcertain

Problem

I've got a dict that has a whole bunch of entries. I'm only interested in a select few of them. Is there an easy way to prune all the other ones out?

Solution

Constructing a new dict:

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


Uses dictionary comprehension.

If you use a version which lacks them (ie Python 2.6 and earlier), make it dict((key, old_dict[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(old_dict) - set(your_keys)
for unwanted_key in unwanted: del your_dict[unwanted_key]

Code Snippets

dict_you_want = {key: old_dict[key] for key in your_keys}
unwanted = set(old_dict) - set(your_keys)
for unwanted_key in unwanted: del your_dict[unwanted_key]

Context

Stack Overflow Q#3420122, score: 1030

Revisions (0)

No revisions yet.