A follow up on the recent question Remove keys from object not in a list in python?
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.