【问题标题】:Getting error as string indices must be integers while using for loop in python在 python 中使用 for 循环时,字符串索引必须是整数
【发布时间】: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


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 2020-08-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-03-26
    • 2016-02-17
    • 2023-03-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多