首页 > 解决方案 > 根据字典的键过滤字典

问题描述

我有一本字典,其键是字符串,值是数字。我还有另一个字符串列表。如果键是字符串列表中的字符串,我想通过删除所有键值对来过滤字典。

例如:dict={"good":44,"excellent":33,"wonderful":55}, randomList=["good","amazing","great"]那么该方法应该给出newdict={"excellent":33,"wonderful":55}

我想知道是否有一种方法可以使用很少的代码来做到这一点。有没有办法快速做到?

标签: python

解决方案


这段简单的代码可以满足您的需求

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


推荐阅读