2 回答
TA贡献1789条经验 获得超10个赞
这段简单的代码可以满足您的需求
oldDict={"good":44,"excellent":33,"wonderful":55}
randomList=["good","amazing","great"]
for word in randomList:
if word in oldDict:
oldDict.pop(word)
print(oldDict)
newDict = oldDict # Optional: If you want to assign it to a new dictionary
# But either way this code does what you want in place
TA贡献1725条经验 获得超8个赞
遍历字典并删除不在列表中的键值对:
d = {'foo': 0, 'bar': 1, 'foobar': 2}
list_of_str = ['foo', 'bang']
{k:v for k, v in d.items() if k not in list_of_str}
输出:
Out[34]: {'bar': 1, 'foobar': 2}
或者如果你list_of_str的更小,这会更快:
d = {'foo': 0, 'bar': 1, 'foobar': 2}
list_of_str = ['foo', 'bang']
for s in list_of_str:
try:
del d[s]
except KeyError:
pass
输出:
Out[41]: {'bar': 1, 'foobar': 2}
添加回答
举报
