【问题标题】:How to loop through this Python dict and search if value is there如何遍历这个 Python dict 并搜索值是否存在
【发布时间】:2017-12-19 21:42:47
【问题描述】:

我有一个这样的 Python 字典:

{
    'TagList': [
        {
            'Key': 'tag1',
            'Value': 'val'
        },
        {
            'Key': 'tag2',
            'Value': 'val'
        },
        {
            'Key': 'tag3',
            'Value': 'val'
        },
        ...
    ]
}

我如何遍历这个字典来搜索Key tag1 是否可用。

编辑:@Willem Van Onsem 的解决方案效果很好。但是我忘了说我需要检查超过1个Key,例如:

If Tag1 and Tag2 exist => true
If either Tag1 or Tag2 is missing` => false

【问题讨论】:

  • 您的字典中的键是否比'TagList' 多?
  • 没有像 TagList 这样的只有 1 个键

标签: python json python-2.7 dictionary


【解决方案1】:

如果您将您的dictionary 声明为a_dict,那么他们就是找到Key tag1 的另一种方式。如果找到那么它将return True 否则False

tag_list = a_dict['TagList']
result = next((True for item in tag_list if item["Key"] == "tag1"),False)
print(result)

对于多个:

a,b=next((True for item in tag_list if item["Key"] == "ta1"),False),\
    next((True for item in tag_list if item["Key"] == "tag2"), False)
result = a and b
print(result)

【讨论】:

    【解决方案2】:

    假设您的字典包含一个键 'TagList' 并且您只对与该键关联的列表中的字典感兴趣,您可以使用:

    any(subd.get('Key') == 'tag1' for subd in the_dict['TagList'])
    

    the_dict 是您要检查的字典。

    因此,我们将 any(..) 内置函数与生成器表达式一起使用,该表达式遍历与 'TagList' 键关联的列表。对于每个这样的子字典,我们检查键 'Key' 是否与值 'tag1' 相关联。如果一个或多个子词典中没有键 'Key',这不是问题,因为我们使用 .get(..)

    对于您给定的字典,这会生成:

    >>> any(subd.get('Key') == 'tag1' for subd in the_dict['TagList'])
    True
    

    多个值

    如果要检查列表的所有值是否出现在子字典中,我们可以使用以下两行(假设“标签名称”是可散列的,字符串是可散列的):

    tag_names = {subd.get('Key') for subd in the_dict['TagList']}
    all(tag in tag_names for tag in ('tag1','tag2'))
    

    这里all(..) 将返回True,如果所有右侧元组中的标记名称 (('tag1','tag2')) 每个都在至少一个子字典中。

    例如:

    >>> all(tag in tag_names for tag in ('tag1','tag2'))
    True
    >>> all(tag in tag_names for tag in ('tag1','tag2','tag3'))
    True
    >>> all(tag in tag_names for tag in ('tag1','tag2','tag4'))
    False
    

    【讨论】:

    • 谢谢,这个单行解决方案效果很好。我可以在这段代码中添加另一个条件来检查 tag1 "和" tag2 是否都存在?
    • @Casper:这是一个更难的问题。但这是可能的。我将编辑答案。
    • 哇,非常感谢,我从来不知道 Python 的这些优雅功能,现在我可以摆脱那些 for 循环了...
    • @WillemVanOnsem 嗨,威廉,我偶然发现了这种新格式,目前的答案似乎并不适用。 { 'Tags': { 'Key': 'Value' } } 我想检查值 'Key' 是否与我的搜索键匹配
    • @Casper:请编辑您的问题,或者提出一个新问题。
    【解决方案3】:
    from collections import ChainMap
    
    'tag1' in ChainMap(*d['TagList'])
    

    或者如果你想要 tag1 的值

    ChainMap(*d['TagList'])['tag1']
    

    【讨论】:

      【解决方案4】:

      您可以使用以下循环:

      for key in d:
          for item in d[key]:
              for deep_key in item:
                  if item[deep_key] == 'tag1': # whatever you are looking for
                      print('Found')
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-24
        • 2013-06-02
        • 2018-03-16
        • 1970-01-01
        • 2022-11-02
        • 2021-12-13
        • 2010-09-27
        相关资源
        最近更新 更多