簡體   English   中英

在 python 中使用 for 循環時,字符串索引必須是整數

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM