python - 如何为字典写条件?
问题描述
我有一本字典,在这本字典中我有不同的键。我想打印其中一些具有一个特定字段的字段,例如我想用 key='d' 打印那些字段
{'a' : 1 ,'b' : 2, 'c' :3}
{'a': 2, 'b' : 33 , 'c' : 44 , 'd' : 56 , 'e' : 78}
{'a' : 4 ,'b' : 6, 'c' :7}
{'a': 66, 'b' : 23 , 'c' : 1 , 'd' : 3 , 'e' : 6}
一种方法是使用
for key in example.keys():
if key='d':
print example
但通过这种方式,我搜索所有关键。我认为它必须有一些更简单的解决方案,而不使用 for 和 if。有人有几点吗?
解决方案
我不知道您的问题的所有细节,但是如果您只想获取具有特定键的字典,您可以执行以下操作
def show_images():
for image in list_images():
image_type = image.get("image_type", None)
if image_type == "snapshot":
print(image)
现在,如果您想查看是否有任何键具有snapshot
值,那么您可以这样做(如评论中所建议)
def show_images():
for image in list_images():
if "snapshot" in image.values():
print(image)
推荐阅读
- listview - ExpansionTile 内的 ListView 不起作用
- go - sync.Waitgroup 不会阻止执行
- python - 正则表达式仅匹配用逗号分隔的唯一名称
- javascript - Jquery Smooth Scrolling 跳转而不是滚动 - 我该如何解决?
- wordpress - 如何在我的商店页面(列出所有产品的页面)上缩小我的特征图像的大小(不是文件大小)?
- python - Serpy .to_represenatiaon
- node.js - MongoDB 聚合和增长
- r - 在 R 中使用 cat() 函数时如何避免空向量?
- html - 使用 ImportXML 导入谷歌表格中的表格
- angular - Angular:使用样式类从组件访问元素