简体   繁体   English

在 python 中使用 for 循环时,字符串索引必须是整数

[英]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 循环:

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.有人可以帮我找出 for 循环中的错误吗? I am new to python.我是 python 的新手。 Thanks谢谢

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我假设 out 是 dict,所以我针对out运行 for 循环

as @TimRoberts suggested, i ran for loop against cdpnei which is actual dictionary正如@TimRoberts 建议的那样,我针对实际字典中的cdpnei运行 for 循环

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM