![](/img/trans.png)
[英]Python for loop json.loads error string indices must be integers
[英]Getting error as string indices must be integers while using for loop in python
我有一个字典列表:
出去:
[
{
"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 的新手。 谢谢
cdpnei = ssh.send_command('show cdp neigh detail', use_textfsm=True)
out = json.dumps(cdpnei, indent = 4)
我假设 out 是 dict,所以我针对out
运行 for 循环
正如@TimRoberts 建议的那样,我针对实际字典中的cdpnei
运行 for 循环
for i in cdpnei:
print('port:'+i['local_port'],'--->','nei_host:'+i['dest_host'],'--->','nei_port:'+i['remote_port'])
这起到了作用,按预期工作。
port:G0/2 --> nei_host:AA ---> nei_port:E1/48
port:G0/1 --> nei_host:BB ---> nei_port:E1/40
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.