tags:

views:

110

answers:

3

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?

+5  A: 

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.

jnnnnn
except I'd probably use `if key in ('x','y','z')` I guess.
Mark
+9  A: 

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, 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(your_dict) - set(keys)
for unwanted_key in unwanted: del your_dict[unwanted_key]
delnan
Didn't know you could do dict-comprehensions too... nifty! This is a pretty nice solution.
Mark
+2  A: 

Given your original dictionary orig and the set of entries that you're interested in keys:

filtered = dict(zip(keys, [orig[k] for k in keys]))

which isn't as nice as delnan's answer, but should work in every Python version of interest. It is, however, fragile to each element of keys existing in your original dictionary.

Kai
Well, this is basically an eager version of the "tuple generator version" of my dict comprehension. Very compatible indeed, though generator expressions were introduced in 2.4, spring 2005 - seriously, is anyone still using this?
delnan
I don't disagree; 2.3 really shouldn't exist anymore. However, as an outdated survey of 2.3 usage: http://moinmo.in/PollAboutRequiringPython24Short version: RHEL4, SLES9, shipped with OS X 10.4
Kai