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?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Constructing a new dict:
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_dict
s 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:
Given your original dictionary
orig
and the set of entries that you're interested inkeys
: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.Short form:
As most of the answers suggest in order to maintain the conciseness we have to create a duplicate object be it a
list
ordict
. This one creates a throw-awaylist
but deletes the keys in originaldict
.You can do that with project function from my funcy library:
Also take a look at select_keys.
Another option:
But you get a
list
(Python 2) or an iterator (Python 3) returned byfilter()
, not adict
.