运行时错误:词典在迭代过程中更改了大小

时间:2019-04-09 18:56:06

标签: dictionary

我遍历字典“ var_dict”的各项。 然后,当我在for循环中迭代时,我需要更新字典。 我知道这是不可能的,并且会触发我遇到的运行时错误。

我的问题是,我是否需要创建其他字典来存储数据?到目前为止,我正在尝试使用具有不同键的相同字典。

我知道问题与通过字典的键和值进行迭代并尝试对其进行更改有关。我想知道是否在这种情况下最好的选择是创建单独的字典。

 for k, v in var_dict.items():
                           match = str(match)
                           match = match.strip("[]")
                           match = match.strip("''")
                           result = [index for index, value in enumerate(v) if match in value]
                           result = str(result)
                           result = result.strip("[]")
                           result = result.strip("'")
                           #====> IF I print(var_dict), at this point I have no error *********  
                           if result == "0":
                               #It means a match between interface on  RP PSE2 model was found; Interface position is on PSE2 architecture
                               print (f'PSE-2 Line cards:{v}     Interfaces on PSE2:{entry}   Interface PortID:{port_id}')
                               port_id = int(port_id)
                               print(port_id)

                               if port_id >= 19:
                                   #print(f'interface:{entry}  portID={port_id}   CPU_POS={port_cpu_pos}    REPLICATION=YES')
                                   if_info = [entry,'PSE2=YES',port_id,port_cpu_pos,'REPLICATION=YES']
                                   var_dict['IF_PSE2'].append(if_info)
                                   #===> *** This is the point that if i attempt to print var_dict, I get the Error during olist(): dictionary changed size during iteration
                               else:
                                   #print(f'interface:{entry},portID={port_id}   CPU_POS={port_cpu_pos}     REPLICATION=NO')
                                   if_info = [entry,'PSE2=YES',port_id,port_cpu_pos,'REPLICATION=NO']
                                   var_dict['IF_PSE2'].append(if_info)
                           else:
                                #it means the interface is on single PSE. No replication is applicable. Just check threshold between incoming and outgoing rate.
                                if_info = [entry,'PSE2=NO',int(port_id),port_cpu_pos,'REPLICATION=NO']

                                var_dict['IF_PSE1'].append(if_info)

1 个答案:

答案 0 :(得分:0)

我做了一个浅表副本,这使我可以迭代字典副本并对原始字典进行修改。问题解决了。谢谢。

(...)  temp_var_dict = var_dict.copy()

        for k, v in temp_var_dict.items():

(...)