猿问

根据字典的键过滤字典

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

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

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


潇湘沐
浏览 195回答 2
2回答

至尊宝的传说

这段简单的代码可以满足您的需求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

qq_遁去的一_1

遍历字典并删除不在列表中的键值对: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}
随时随地看视频慕课网APP

相关分类

Python
我要回答