Filtering Python dictionaries

Here’s a little Python snippet I just made up, but is immensely useful because I couldn’t find an obvious method like filter that applied to dictionaries instead of lists. This code pulls out specific key-value pairs from a dictionary and puts them in a new dictionary.

[cce lang="Python"]
>>> x={ ‘test1′:1, ‘test2′:2, ‘test3′:3 }
>>> my_keys = (‘test1′,’test2′)
>>> y=dict(filter(lambda t: t[0] in my_keys, x.items()))
{‘test’: 1, ‘test2′: 2}
[/cce]

Obviously the performance characteristics of this won’t scale, but if you just want a few keys out of a dictionary then you should be fine.



0 comments ↓

There are no comments yet...Kick things off by filling out the form below..

Leave a Comment

Powered by WP Hashcash