[英]How to remove elements from a Python dictionary based on elements in a list?
I have a list of tuples: 我有一个元组列表:
lst=[(6, 'C'), (6, 'H'), (2, 'C'), (2, 'H')]
And a dictionary: 还有一本字典:
dct={'6C': (6, 'C'), '6H': (6, 'H'), '9D': (9, 'D'), '10D': (10, 'D'), '11S': (11, 'S'), '2C': (2, 'C'), '2H': (2, 'H')}
How can I remove the elements from the dictionary that are in the list? 如何从列表中删除列表中的元素? In this example my desired output would be:
在这个例子中,我想要的输出是:
dct2={'9D': (9, 'D'), '10D': (10, 'D'), '11S': (11, 'S')}
我会使用字典理解来映射键与列表中找不到的值:
new_dict = {k: v for k, v in old_dict.items() if v not in the_list} # filter from the list
If you're on Python 2 try this: 如果您使用的是Python 2,请尝试以下操作:
for key, value in dct.items():
if value in lst:
del dct[key]
EDIT: 编辑:
A solution that works in both Python 2 and 3: 适用于Python 2和3的解决方案:
dict((key, value) for key, value in dct.items() if value not in lst)
Using the valfilter
function from toolz : 使用
valfilter
函数 :
from toolz import valfilter
valfilter(lst.__contains__, dct)
I would make the lst
set before filtering out elements, since it is data structure which let's you test if element is present more efficiently. 我会在过滤掉元素之前设置第一个
lst
,因为它是数据结构,让你测试元素是否更有效。
purge_set = set(lst)
dict(filter(lambda (k, v): v not in purge_set, dct.iteritems()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.