python - 循环遍历python中的嵌套字典
问题描述
我希望遍历以下 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 循环时,我得到了错误。
解决方案
I see two problems. 1) there is space between u an field in your dictionary which will cause issue.
2) because result is a list and under that hosts is another list, you should iterate through both the lists
for eachresult in hgetjsonObject['result']:
for eachhost in eachresult['hosts']:
print(eachhost['hostid'],eachhost['name'])
Output:
10394 vsclap01l 10395 vsclap03l 10396 vscldb04l
推荐阅读
- apache-kafka - 使用 Spring 的 KafkaListener 优于 Apache 的 KafkaConsumer 的优势?
- python - 过滤并仅保留具有相同索引的行
- flutter - Flutter Linkfiy - 不包含链接文本的方法?
- python - 试图使列的顺序与第一个参数中的键顺序相同(python)
- python - 一个单词的 Python 正则表达式
- javascript - 'object HTMLCollection' 而不是来自 RSS 的图像 URL
- python - AttributeError:尝试将张量转换为 nparray 时,“张量”对象没有属性“numpy”
- python - Python If 语句评估为真,但不执行?
- c++ - 何时使用带有 target_include_directories 的 BUILD_INTERFACE 和 INSTALL_INTERFACE 生成器表达式?
- cmake - 什么 cmake 命令会将文件目录复制到构建后步骤中的目录