在Python中迭代时如何解决字典的变化大小 [英] How to solve dictionary changed size during iteration in Python
问题描述
为key,value在dictionary.items()中:
为key1,value1在dictionary.items()中:
如果key1!= key和value> value1:
dictionary.pop(key)
打印(字典)
其中结果
RuntimeError:字典在迭代期间更改大小
如何避免这个错误?
替代解决方案
如果您要查找字典中的最小值,您可以执行以下操作:
min(dictionary.values())
如果不能使用min,可以使用排序:
sorted(dictionary.values())[0]
为什么会收到此错误?
在旁注中,您遇到运行时错误
是在内循环中修改外循环的迭代器。当您 pop
一个尚未被外部循环访问的条目,外部迭代器到达它时,它尝试访问已删除的元素,从而导致错误。 >
如果您尝试在Python 2.7(而不是3.x)上执行代码,实际上会得到一个键错误
。
我可以做些什么来避免错误?
如果要修改可迭代在基于其迭代器的循环内,您应该使用深层复制。
I want pop out all the large values and its keys in a dictionary, and keep the smallest. Here is the part of my program
for key,value in dictionary.items():
for key1, value1 in dictionary.items():
if key1!= key and value > value1:
dictionary.pop(key)
print (dictionary)
Which results in
RuntimeError: dictionary changed size during iteration
How can I avoid this error?
Alternative solutions
If you're looking for the smallest value in the dictionary you can do this:
min(dictionary.values())
If you cannot use min, you can use sorted:
sorted(dictionary.values())[0]
Why do I get this error?
On a side note, the reason you're experiencing an Runtime Error
is that in the inner loop you modify the iterator your outer loop is based upon. When you pop
an entry that is yet to be reached by the outer loop and the outer iterator reaches it, it tries to access a removed element, thus causing the error.
If you try to execute your code on Python 2.7 (instead of 3.x) you'll get, in fact, a Key Error
.
What can I do to avoid the error?
If you want to modify an iterable inside a loop based on its iterator you should use a deep copy of it.
这篇关于在Python中迭代时如何解决字典的变化大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!