如何为字典写条件?

时间:2019-04-27 10:04:30

标签: python performance dictionary

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

2 个答案:

答案 0 :(得分:1)

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

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)

答案 1 :(得分:0)

已编辑

def show_images():
    for image in list_images():
        for key in image.keys():
            if image[key] == "snapshot":
                print(image)
                break