python :- IndexError: list index out of range when converting list into dictionary

python :- IndexError: list index out of range when converting list into dictionary

想法是将 "netsh wlan show interfaces" 的输出放入字典中,以便可以根据键获取值。

观察到的错误是:

IndexError: list index out of range

import subprocess
results = subprocess.check_output("netsh wlan show interfaces")
results = results.decode("ascii")
results = results.replace("\r","")
ls = results.split("\n")
ls = ls[3:]
dict = {}
temp = []

for i in ls:
    temp = i.split(":")
    m = temp[0].strip()
    dict[m] = temp[1].strip()

print(dict)

命令输出的每一行中可能没有 ":",因此在假设列表中有多个项目之前,您应该使用 if 语句来确保它确实存在i.split(":") 返回:

for i in ls:
    temp = i.split(":", 1)
    if len(temp) > 1:
        m = temp[0].strip()
        dict[m] = temp[1].strip()