'Getting error as string indices must be integers while using for loop in python
i have a list of dict as:
out:
[
{
"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": ""
}]
this is my for loop:
for i in out:
print('port:'+i['local_port'],'--->','nei_host:'+i['dest_host'],'--->','nei_port:'+i['remote_port'])
error -
print('port:'+i['local_port'],'--->','nei_host:'+i['dest_host'],'--->','nei_port:'+i['remote_port'])
TypeError: string indices must be integers
what i would like to print:
port:G0/2 --> nei_host:AA ---> nei_port:E1/48
port:G0/1 --> nei_host:BB ---> nei_port:E1/40
Can some one help me to find the error in for loop. I am new to python. Thanks
Solution 1:[1]
cdpnei = ssh.send_command('show cdp neigh detail', use_textfsm=True)
out = json.dumps(cdpnei, indent = 4)
i was assuming out is dict, so i was running for loop against out
as @TimRoberts suggested , i ran for loop against cdpnei which is actual dictionary
for i in cdpnei:
print('port:'+i['local_port'],'--->','nei_host:'+i['dest_host'],'--->','nei_port:'+i['remote_port'])
that did a trick, worked as expected.
port:G0/2 --> nei_host:AA ---> nei_port:E1/48
port:G0/1 --> nei_host:BB ---> nei_port:E1/40
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | netv |
