【问题标题】:For loop is overwriting dictionary values in list [duplicate]For循环正在覆盖列表中的字典值[重复]
【发布时间】: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


【解决方案1】:

问题是由于列表的附加。当您附加一个项目时(在您的情况下是一个字典)。它不创建字典,但它只是放置引用。

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

【讨论】:

    【解决方案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)
    

    【讨论】:

    • 当有no副本时不能是“同一个副本”...
    • 你在说什么?原始代码中有一个字典的副本。不,字典没有经过 .copy() 处理,但它是字典的副本。
    • 我不知道怎么做。这是哪个字典的副本?
    • 内置dict()的一个副本
    【解决方案3】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-02-13
      • 2017-12-25
      • 1970-01-01
      • 2019-05-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多