【发布时间】:2018-06-01 06:04:13
【问题描述】:
问题
我已经创建了一个 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'
【问题讨论】:
-
它与
for循环本身没有太大关系:列表包含对 same 字典的两个引用。 -
所以你是说我必须使用索引号来创建一个新字典并将值附加到与字典相关的索引号?
-
不,也和使用索引无关,每次都要构造一个new字典。
-
或者您可以使用
listofdevices.append(device.copy())附加设备副本 -
您只是每次都在修改和附加同一个字典。而是在每次迭代时创建一个新的。
标签: python dictionary for-loop