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

Dan*_*son 5 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)
Run Code Online (Sandbox Code Playgroud)

示例代码

第一个内容索引是:

x[0] = '10.10.10.1'
x[1] = 'aa:bb:cc:dd'
Run Code Online (Sandbox Code Playgroud)

第二个内容索引是:

x[0] = '20.20.20.1'
x[1] = 'qq:ww:ee:ee:rr'
Run Code Online (Sandbox Code Playgroud)

实际发生了什么

  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'
Run Code Online (Sandbox Code Playgroud)

Dem*_*iOS 1

您并不是每次都创建一个新的字典对象。您只需在每次迭代中改变同一对象即可。尝试使用该模块深度复制字典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)
Run Code Online (Sandbox Code Playgroud)