为了账号安全,请及时绑定邮箱和手机立即绑定

根据字典的键过滤字典

根据字典的键过滤字典

潇湘沐 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 关注
  • 194 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号