gpt4 book ai didi

python - For 循环正在覆盖列表中的字典值

转载 作者:太空狗 更新时间:2023-10-30 01:19:18 27 4
gpt4 key购买 nike

<分区>

问题

我做了一个 for 循环来读取列表的内容,但是当将两个值分配给字典然后将该输出附加到列表时,下一个值会覆盖列表中的所有内容

期望的结果

我想将多个字典附加到一个列表中,所以当我运行 for 循环并打印与“ip”相关的所有内容时,它将打印与字典值“ip”关联的所有值。

代码

device =  { 'ip': '', 'mac': '', 'username': 'admin', 'password': [], 'device type': '', }
listofdevices = []
def begin():
file = open("outputfromterminal")
contents = file.read()
contents = contents.split(',')[1:]
for x in contents:
# do some text stripping
x = x.split(' ')
device['ip']=x[0]
device['mac']=x[1]
listofdevices.append(device)

示例代码

目录的第一个索引是:

x[0] = '10.10.10.1'
x[1] = 'aa:bb:cc:dd'

目录的第二个索引是:

x[0] = '20.20.20.1'
x[1] = 'qq:ww:ee:ee:rr'

实际发生了什么

  listofdevices[0] 'ip': 20.20.20.1, 'mac': 'qq:ww:ee:ee:rr'
listofdevices[1] 'ip': 20.20.20.1, 'mac': 'qq:ww:ee:ee:rr'

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com