for循环覆盖列表中的字典值[重复]

问题描述 投票:5回答:3

这个问题在这里已有答案:

问题

我已经创建了一个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'
python dictionary for-loop
3个回答
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)

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)

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)
© www.soinside.com 2019 - 2024. All rights reserved.