For循环覆盖列表中的字典值

时间:2017-12-18 20:49:13

标签: python dictionary for-loop

问题

我已经创建了一个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'

3 个答案:

答案 0 :(得分:2)

试试这段代码。每台设备都试图编辑相同的字典副本。

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)

答案 1 :(得分:0)

每次都没有创建新的字典对象。您只是在每次迭代中改变相同的对象。尝试使用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)

答案 2 :(得分:0)

问题是由于附加了清单。附加项目时(在您的情况下是字典)。它不会创建字典,但它只是放置引用。

如果你每次都可以在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)