对于循环,是列表中覆盖字典值



essue

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

所需的结果

我想将多个字典附加到列表中,因此当我运行循环并打印与" 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'

尝试此代码。每个设备都试图编辑字典的相同副本。

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

您并非每次都创建一个新的词典对象。您只是在每次迭代中只是突变相同的对象。尝试使用copy模块深层复制字典。然后,在获得此副本后,将其变异并附加到列表:

import copy
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:
     device = copy.deepcopy(device) #creates a deep copy of the values of previous dictionary.  
     #device now references a completely new object
     # do some text stripping
     x = x.split(' ')
     device['ip']=x[0]
     device['mac']=x[1]
     listofdevices.append(device)

问题是由于列表的附加量。当您附加项目时(在您的情况下是字典)。它不会创建字典,而只是放置参考。

如果您每次都可以在for循环中初始化字典,则应创建新的参考。

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': '', 'mac': '', 'username': 'admin', 'password': [], 'device type': '', }
     device['ip']=x[0]
     device['mac']=x[1]
     listofdevices.append(device)

最新更新