【发布时间】:2022-01-27 01:05:08
【问题描述】:
我有一个字典列表:
出来:
[
{
"dest_host": "AA",
"sysname": "",
"mgmt_ip": "1.1.1.1",
"platform": "switch",
"remote_port": "E1/48",
"local_port": "G0/2",
"version": "",
"interface_ip": ""
},
{
"dest_host": "BB",
"sysname": "",
"mgmt_ip": "1.1.1.2",
"platform": "switch",
"remote_port": "E1/40",
"local_port": "G0/1",
"version": "",
"interface_ip": ""
}]
这是我的 for 循环:
for i in out:
print('port:'+i['local_port'],'--->','nei_host:'+i['dest_host'],'--->','nei_port:'+i['remote_port'])
错误-
print('port:'+i['local_port'],'--->','nei_host:'+i['dest_host'],'--->','nei_port:'+i['remote_port'])
TypeError: string indices must be integers
我想打印什么:
port:G0/2 --> nei_host:AA ---> nei_port:E1/48
port:G0/1 --> nei_host:BB ---> nei_port:E1/40
有人可以帮我找出 for 循环中的错误吗?我是 python 新手。谢谢
【问题讨论】:
-
这是你的全部代码吗?它非常适合我
-
顺便说一句,
out不是你声称的那样。使用print(repr(out))确定。 -
out是明确的字典,还是 JSON 字符串? -
@csjh 我有
out = json.dumps(cdpnei, indent = 4),当我打印(输出)时,我确实看到了 dict 列表,所以我假设 out 是一个字典。 -
没有。
out是一个字符串。字符串看起来像字典,因为这就是 JSON 所做的,但字典是cdpnei。
标签: python python-3.x for-loop