[英]loop through nested dictionary in python
I wish to loop through the following json dictionary: 我希望遍历以下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
}
Here is what I have tried so far: 到目前为止,这是我尝试过的:
print(hgetjsonObject['result'][0]['hosts'][0])
But when I run it, it aborts with the following: 但是,当我运行它时,它会中止以下操作:
{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
I want to be able to do something like this: 我希望能够做这样的事情:
for eachhost in hgjsonObject['result']:
print(eachhost['hostid'],eachhost['name'])
When I run the for loop, I get errors. 当我运行for循环时,出现错误。
I see two problems. 我看到两个问题。 1) there is space between u an field in your dictionary which will cause issue.
1)您的字典中的字段之间存在空格,这会引起问题。
2) because result is a list and under that hosts is another list, you should iterate through both the lists 2)由于result是一个列表,而该主机下的是另一个列表,因此您应该遍历两个列表
for eachresult in hgetjsonObject['result']:
for eachhost in eachresult['hosts']:
print(eachhost['hostid'],eachhost['name'])
Output: 输出:
10394 vsclap01l 10395 vsclap03l 10396 vscldb04l 10394 vsclap01l 10395 vsclap03l 10396 vscldb04l
for access to hosts
key iterate in this way: 以这种方式访问
hosts
密钥:
>>> for eachhost in hgetjsonObject['result'][0]['hosts']:
print(eachhost["hostid"], eachhost["name"])
('10394', 'vsclap01l')
('10395', 'vsclap03l')
('10396', 'vscldb04l')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.