python - 根据字典的键过滤字典
问题描述
我有一本字典,其键是字符串,值是数字。我还有另一个字符串列表。如果键是字符串列表中的字符串,我想通过删除所有键值对来过滤字典。
例如:dict={"good":44,"excellent":33,"wonderful":55}, randomList=["good","amazing","great"]
那么该方法应该给出newdict={"excellent":33,"wonderful":55}
我想知道是否有一种方法可以使用很少的代码来做到这一点。有没有办法快速做到?
解决方案
这段简单的代码可以满足您的需求
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
推荐阅读
- r - 如何使用 r 中的管道工在同一请求中返回图像和数据
- java - 进度计数未显示 100%
- node.js - Nodemon 错误:已达到文件观察者数量的系统限制
- javascript - 使用 JavaScript 为事件侦听器添加冷却时间
- c# - 自动代理切换器 WInform (C#)
- django - 我们可以在 Django 的 models.py 中定义数据库名称吗?
- vba - 如何从 OneNote 表格中获取数据到 Outlook 宏?
- leaflet - 在 TomTom 地图上显示路线的总道路距离
- c# - 由两个对象组成的对象
- html - 如何使用 css 正确实现边框图像?