[英]RuntimeError: OrderedDict mutated during iteration (Python3)
Getting the error mentioned in the title. 获取标题中提到的错误。 The below mentioned functioned is called by another function that is called through a POST api.
下面提到的函数由另一个通过POST api调用的函数调用。
Error is on the line below the print statement. 错误在print语句下面的行上。 Dont know what the error means and why its coming.
不知道错误意味着什么以及它为什么会出现。 The same code used to run a week back.
用于运行一周的相同代码。
def remove_individual_stops(ordered_parkstop_dict, relevant_data):
new_ordered_parkstop_dict = ordered_parkstop_dict
for key, value in ordered_parkstop_dict.items():
if len(value) == 0:
for k,v in ordered_parkstop_dict.items():
if key in v:
new_ordered_parkstop_dict.pop(key)
print (type(ordered_parkstop_dict), ordered_parkstop_dict)
for k,v in ordered_parkstop_dict.items():
klist = []
keylist = []
if value and v:
if len(v)==1 and len(value)==1:
klist.append(k), keylist.append(key)
if (keylist == v) and (klist == value and len(value) == 1):
new_ordered_parkstop_dict.pop(key)
return new_ordered_parkstop_dict
You assigned new_ordered_parkstop_dict
with a reference of the ordered_parkstop_dict
dict, so when you iterate over ordered_parkstop_dict.items()
and mutate new_ordered_parkstop_dict
by popping it, you mutate ordered_parkstop_dict
too, which can't be done since your loop is iterating over ordered_parkstop_dict
. 你为
new_ordered_parkstop_dict
分配了ordered_parkstop_dict
dict的引用,所以当你遍历ordered_parkstop_dict.items()
并通过弹出它来改变new_ordered_parkstop_dict
时,你也会改变ordered_parkstop_dict
,这是因为你的循环遍历ordered_parkstop_dict
而无法完成。
You should assign a copy of ordered_parkstop_dict
to new_ordered_parkstop_dict
instead. 您应该将
ordered_parkstop_dict
的副本分配给new_ordered_parkstop_dict
。 Change: 更改:
new_ordered_parkstop_dict = ordered_parkstop_dict
to: 至:
new_ordered_parkstop_dict = ordered_parkstop_dict.copy()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.