如何使用python2从rest输出访问字段值?

时间:2019-03-06 20:36:40

标签: python python-2.7 jython

这是我的结构:

[
            {
                "name": "ga0",
                "fullName": "gac0",
                "key": "office"
                "id" : "Apps/tex3435",
                "value" : "test2"
            },
            {
                "name": "gasec1",
                "fullName": "gasec1",
                "key": "PRINCIPAL"
                "id" : "Apps/tex3433",
                "value" : "test"
            }
]

我想获取键PRINCIPAL的ID。

2 个答案:

答案 0 :(得分:2)

此解决方案返回r中具有l的条目的列表key = PRINCIPAL

l = [
            {
                "name": "ga0",
                "fullName": "gac0",
                "key": "office",
                "id" : "Apps/tex3435",
                "value" : "test2"
            },
            {
                "name": "gasec1",
                "fullName": "gasec1",
                "key": "PRINCIPAL",
                "id" : "Apps/tex3433",
                "value" : "test"
            }
]

r = filter(lambda k: k['key']=="PRINCIPAL", l)
print(r[0]['id'])

答案 1 :(得分:2)

一个简单的循环,用于获取值>“ PRINCIPAL”的键:

d = [
{
"name": "ga0",
"fullName": "gac0",
"key": "office",
"id" : "Apps/tex3435",
"value" : "test2"
},   
{
"name": "gasec1",
"fullName": "gasec1",
"key": "PRINCIPAL",
"id" : "Apps/tex3433",
"value" : "test"
}]

for x in d:

    # x is a dictionary, so we now iterate over its key - value pair
    # Use x.iteritems() for Python 2

    for key, values in x.items():
        if values == 'PRINCIPAL':
            print(key)

# Using list comprehension
print([i for x in d for i, j in zip(x.keys(), x.values()) if j == 'PRINCIPAL'])