如何解决字典在迭代错误时更改大小的问题? [英] How to solve dictionary changed size during iteration error?

查看:101
本文介绍了如何解决字典在迭代错误时更改大小的问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在字典中弹出所有较大的值及其键,并保持最小的值.这是我程序的一部分

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)  

会导致

RuntimeError: dictionary changed size during iteration    

如何避免此错误?

推荐答案

替代解决方案

如果您正在寻找字典中的最小值,则可以执行以下操作:

Alternative solutions

If you're looking for the smallest value in the dictionary you can do this:

min(dictionary.values())

如果不能使用min,则可以使用sorted:

If you cannot use min, you can use sorted:

sorted(dictionary.values())[0]

为什么会出现此错误?

另一方面,您遇到Runtime Error的原因是,在内部循环中您修改了外部循环所基于的迭代器.当您pop外循环尚未到达的条目且外迭代器到达该条目时,它会尝试访问已删除的元素,从而导致错误.
如果您尝试在Python 2.7(而不是3.x)上执行代码,则实际上会得到Key Error.

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.

如果要基于迭代器的 iterator 修改循环中的 iterable ,则应使用

If you want to modify an iterable inside a loop based on its iterator you should use a deep copy of it.

这篇关于如何解决字典在迭代错误时更改大小的问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆