如何遍历这个Python dict并搜索值是否存在

Cas*_*per 2 python json dictionary python-2.7

我有一个像这样的Python字典:

{
    'TagList': [
        {
            'Key': 'tag1',
            'Value': 'val'
        },
        {
            'Key': 'tag2',
            'Value': 'val'
        },
        {
            'Key': 'tag3',
            'Value': 'val'
        },
        ...
    ]
}
Run Code Online (Sandbox Code Playgroud)

如何遍历此dict以搜索是否Key tag1可用.

编辑:@Willem Van Onsem的解决方案非常有用.但是我忘了提到我需要检查多个Key,例如:

If Tag1 and Tag2 exist => true
If either Tag1 or Tag2 is missing` => false
Run Code Online (Sandbox Code Playgroud)

Wil*_*sem 5

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

any(subd.get('Key') == 'tag1' for subd in the_dict['TagList'])
Run Code Online (Sandbox Code Playgroud)

字典the_dict是您要检查的字典.

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

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

>>> any(subd.get('Key') == 'tag1' for subd in the_dict['TagList'])
True
Run Code Online (Sandbox Code Playgroud)

多个值

如果要检查列表中是否出现列表的所有值,我们可以使用以下两行(假设"标记名称"是可清除的,字符串是可清除的):

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

如果right()中的元组中的所有标记名都在至少一个子字典中,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
Run Code Online (Sandbox Code Playgroud)