Python根据字典中的条件查找obj值

时间:2017-09-27 21:53:44

标签: python dictionary conditional

我从python请求获得json数据:

{
    "results": [
        {
            "name": "virtual-machine-1",
            "guest": "Microsoft Windows Server 2016 (64-bit)",
            "status": "green",
            "id": "567890-004",
        },
        {
            "name": "virtual-machine-2",
            "guest": "CoreOS Linux (64-bit)",
            "status": "green",
            "id": "567890-005",
        }
    ]
}

如何根据“名称”值获取所有词典的“id”值。

我已经看到了基于键查找值的解决方案,但不是在相同字典中的条件基础上,并为多个字典迭代它。感谢您的帮助。

3 个答案:

答案 0 :(得分:2)

重新输入了ID:

>>> {result['id']: result['name'] for result in data['results']}
{'567890-004': 'virtual-machine-1', '567890-005': 'virtual-machine-2'}

此技术称为字典理解

答案 1 :(得分:0)

d = {result['name']: result['id'] for result in request.dict['results'] if 'name' in result}
# request.dict is the name of the object that contains the list "results"

答案 2 :(得分:0)

将您的json转换为词典列表。然后只需使用简写语句。

results = [
{ "name": "virtual-machine-1",
            "guest": "Microsoft Windows Server 2016 (64-bit)",
            "status": "green",
            "id": "567890-004"},
{"name": "virtual-machine-2",
            "guest": "CoreOS Linux (64-bit)",
            "status": "green",
            "id": "567890-005"}
]

id = [x['id'] for x in results if x['name'] == "virtual-machine-1"]
print id    # prints 567890-004

id = [x['id'] for x in results if x['name'] == "virtual-machine-2"]
print id    # prints 567890-005