代码之家  ›  专栏  ›  技术社区  ›  yasin lachini

如何用python编写字典的条件

  •  -3
  • yasin lachini  · 技术社区  · 6 年前

    我有一本字典,在这本字典里我有不同的键。我想打印其中一些有一个特定字段的字段,例如,我想打印那些带有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 回复  |  直到 6 年前
        1
  •  1
  •   Ignacio Vergara Kausel    6 年前

    我不知道你的问题的所有细节,但是如果你只想得到带有某个键的词典,你可以做以下操作

    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)
    
        2
  •  0
  •   Aref    6 年前

    :

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