确定 json 对象是否包含特定值的 Pythonic 方法?

标签 python python-2.7

我有一个从调用返回的 json 对象,类似于:

{
    'Tags': [
        {
            'Key': 'Dept',
            'PropagateAtLaunch': True,
            'ResourceId': 'my-auto-scaling-group',
            'ResourceType': 'auto-scaling-group',
            'Value': 'Research',
        },
        {
            'Key': 'Role',
            'PropagateAtLaunch': True,
            'ResourceId': 'my-auto-scaling-group',
            'ResourceType': 'auto-scaling-group',
            'Value': 'WebServer',
        },
        {
            'Key': 'ecs_scaling',
            'PropagateAtLaunch': True,
            'ResourceId': 'my-auto-scaling-group',
            'ResourceType': 'auto-scaling-group',
            'Value': 'true',
        },
    ],
    'ResponseMetadata': {
        '...': '...',
    },
}

除了标准之外,是否有更 Pythonic 的方法来简单地确定 key ecs_scaling 是否存在:

data = json.loads(theThing)
for key in data.items():
   ... 

key 可以是第一项,也可以是第 40 项——理想情况下,我希望能够执行类似 if 'ecs_scaling' in theKeys: ... 的操作?

最佳答案

您可以使用内置的 any .

Return True if any element of the iterable is true. If the iterable is empty, return False.

if any(tag['key'] == 'ecs_scaling' for tag in data['Tags']):
    ...

关于确定 json 对象是否包含特定值的 Pythonic 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45964144/

相关文章:

如果描述包含列表中的短语,Python Pandas 总结分数

python - ModelSerializer 是否应该按 View 编写?

python - 从静态变量引用静态方法

linux - "python"与 "sudo python"

python - 将值从 python 列表传递到 Cassandra 查询

python - 基于 ID 列表有效计算 XOR(^) 校验和的方法

python - 如何在 Keras 中的每批之后更新训练日志输出?

python - urlopen、BeautifulSoup 和 UTF-8 问题

python - 在没有 json 库的情况下在 python 中解析 JSON 对象(仅使用正则表达式)

python-2.7 - 使用 Python pandas 从电子邮件中提取用户名