第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

根據(jù)字典的鍵過濾字典

根據(jù)字典的鍵過濾字典

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

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


查看完整回答
反對(duì) 回復(fù) 2022-06-28
?
qq_遁去的一_1

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}


查看完整回答
反對(duì) 回復(fù) 2022-06-28
  • 2 回答
  • 0 關(guān)注
  • 123 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)