2 回答

TA貢獻(xiàn)1789條經(jīng)驗(yàn) 獲得超10個(gè)贊
這段簡(jiǎn)單的代碼可以滿足您的需求
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貢獻(xiàn)1725條經(jīng)驗(yàn) 獲得超8個(gè)贊
遍歷字典并刪除不在列表中的鍵值對(duì):
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的更小,這會(huì)更快:
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}
添加回答
舉報(bào)