亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

根據字典的鍵過濾字典

根據字典的鍵過濾字典

瀟湘沐 2022-06-28 10:31:49
我有一本字典,其鍵是字符串,值是數字。我還有另一個字符串列表。如果鍵是字符串列表中的字符串,我想通過刪除所有鍵值對來過濾字典。例如:dict={"good":44,"excellent":33,"wonderful":55}, randomList=["good","amazing","great"]那么該方法應該給出newdict={"excellent":33,"wonderful":55}我想知道是否有一種方法可以使用很少的代碼來做到這一點。有沒有辦法快速做到?
查看完整描述

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


查看完整回答
反對 回復 2022-06-28
?
qq_遁去的一_1

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}


查看完整回答
反對 回復 2022-06-28
  • 2 回答
  • 0 關注
  • 126 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號