循环遍历python中的嵌套字典

问题描述 投票:0回答:2

我想循环通过以下json字典:

hgetjsonObject = {
    u 'jsonrpc': u '2.0', u 'result': [{
        u 'hosts': [{
            u 'status': u '0',
            u 'hostid': u '10394',
            u 'name': u 'vsclap01l'
        }, {
            u 'status': u '0',
            u 'hostid': u '10395',
            u 'name': u 'vsclap03l'
        }, {
            u 'status': u '0',
            u 'hostid': u '10396',
            u 'name': u 'vscldb04l'
        }],
        u 'groupid': u '4',
        u 'name': u 'Zabbix servers'
    }], u 'id': 2
}

这是我到目前为止所尝试的:

print(hgetjsonObject['result'][0]['hosts'][0])

但是当我运行它时,它会中止以下内容:

{u'status': u'0', u'hostid': u'10394', u'name': u'vsclap01l'}
Traceback (most recent call last):
  File "./automaton.py", line 341, in <module>
    print(hgetjsonObject['result'][0]['hosts'][0])
IndexError: list index out of range

我希望能够做到这样的事情:

for eachhost in hgjsonObject['result']:
    print(eachhost['hostid'],eachhost['name'])

当我运行for循环时,我得到错误。

python json
2个回答
1
投票

我看到两个问题。 1)你字典中的字段之间有空格会引起问题。

2)因为结果是一个列表,并且在该主机下是另一个列表,你应该遍历这两个列表

for eachresult in hgetjsonObject['result']:
         for eachhost in eachresult['hosts']:
             print(eachhost['hostid'],eachhost['name'])

输出:

10394 vsclap01l 10395 vsclap03l 10396 vscldb04l


0
投票

以这种方式访问​​hosts密钥迭代:

>>> for eachhost in hgetjsonObject['result'][0]['hosts']:
        print(eachhost["hostid"], eachhost["name"])

('10394', 'vsclap01l')
('10395', 'vsclap03l')
('10396', 'vscldb04l')
© www.soinside.com 2019 - 2024. All rights reserved.