That question turns out to be a duplicate of a previous one. All answers there, and among them the most voted, use list comprehension. I'm thinking on a functional approach. How can this be done using filter?
We have:
testdict={'a':'vala', 'b':'valb', 'c':'valc','d':'vald'}
keep=['a','c']
and I want
filter(isKept,testdict)
to give
{'a':'vala','c':'valc'}
I tried naively defining isKept as a function of either one (the keys) or two variables (keys, values) but the former just filters out the right keys without the corresponding values (i.e., a list, not a dictionary). The latter way doesn't even parse correctly.
Is there a filter for dictionaries in Python?
Notice that testdict.pop(k) is not what I want as this deletes, but the question here is to keep.
解决方案
Truth be told using comprehensions is as functional as it gets, but if that's not what you want toolz library provides a nice set of functions including keyfilter:
>>> from toolz.dicttoolz import keyfilter
>>> to_keep = lambda key: key in set(keep)
>>> keyfilter(to_keep, testdict)
{'a': 'vala', 'c': 'valc'}