Python功能方法:使用过滤器从dict中删除key [英] Python functional approach: remove key from dict using filter
问题描述
关于最近的问题,请删除密钥从python中的对象不在列表中?
该问题与上一个问题重复。所有答案都在那里,其中最投票的,使用列表的理解。我正在考虑一个功能性的方法。如何使用 filter
?
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
?
我们有:
testdict={'a':'vala', 'b':'valb', 'c':'valc','d':'vald'}
keep=['a','c']
我想要
filter(isKept,testdict)
给
{'a':'vala','c':'valc'}
我尝试天真地定义 isKept
作为一个函数(键)或两个变量(键,值),但前者只是滤除右键而不使用相应的值(即列表而不是字典)。后一种方式甚至无法正确解析。
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.
Python中有字典的过滤器吗?
Is there a filter for dictionaries in Python?
请注意,这个删除不是我想要的,而是这个问题, testdict.pop(k)
Notice that testdict.pop(k)
is not what I want as this deletes, but the question here is to keep.
推荐答案
真理被告知使用理解与功能一样,但如果不是你想要的 toolz
库提供了一个很好的设置的功能包括 keyfilter
:
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'}
这篇关于Python功能方法:使用过滤器从dict中删除key的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!