Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python functional approach: remove key from dict using filter

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.

like image 611
MASL Avatar asked Dec 07 '25 07:12

MASL


1 Answers

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'}
like image 108
zero323 Avatar answered Dec 08 '25 21:12

zero323



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!