首页 > 解决方案 > 如何为字典写条件?

问题描述

我有一本字典,在这本字典中我有不同的键。我想打印其中一些具有一个特定字段的字段,例如我想用 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。有人有几点吗?

标签: pythonperformancedictionary

解决方案


我不知道您的问题的所有细节,但是如果您只想获取具有特定键的字典,您可以执行以下操作

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)

推荐阅读