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
This function will do the trick:
Just like delnan's version, this one uses dictionary comprehension and has stable performance for large dictionaries (dependent only on the number of keys you permit, and not the total number of keys in the dictionary).
And just like MyGGan's version, this one allows your list of keys to include keys that may not exist in the dictionary.
And as a bonus, here's the inverse, where you can create a dictionary by excluding certain keys in the original:
Note that unlike delnan's version, the operation is not done in place, so the performance is related to the number of keys in the dictionary. However, the advantage of this is that the function will not modify the dictionary provided.
Edit: Added a separate function for excluding certain keys from a dict.
Based on the accepted answer by delnan.
What if one of your wanted keys aren't in the old_dict? The delnan solution will throw a KeyError exception that you can catch. If that's not what you need maybe you want to:
only include keys that excists both in the old_dict and your set of wanted_keys.
have a default value for keys that's not set in old_dict.
Slightly more elegant dict comprehension:
Here's an example in python 2.6:
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.
Code 1:
Code 2:
Code 3:
All pieced of code performance are measured with timeit using number=1000, and collected 1000 times for each piece of code.
For python 3.6 the performance of three ways of filter dict keys almost the same. For python 2.7 code 3 is slightly faster.
This one liner lambda should work:
Here's an example:
It's a basic list comprehension iterating over your dict keys (i in x) and outputs a list of tuple (key,value) pairs if the key lives in your desired key list (y). A dict() wraps the whole thing to output as a dict object.