我想删除字典中包含特定单词的元素,例如:
my_dict = {
"this is a first example" : 5,
"this is a seconde example" : 3,
"this is a third example" : 2
}
my_list = ["first", "third"]
Run Code Online (Sandbox Code Playgroud)
我想要的结果是这样的:
{'this is a seconde example': 3}
Run Code Online (Sandbox Code Playgroud)
这就是我所做的:
my_new_dict = dict(my_dict)
for sent in my_dict:
for word in sent.split() :
if word in my_list :
del my_new_dict[sent]
break
Run Code Online (Sandbox Code Playgroud)
这个脚本可以工作,但问题是它很长,对于一个大小为 100 万的字典和一个大小为 355K 的单词列表,需要六个多小时。
有没有更好的方法呢?