Python RuntimeError:字典在迭代过程中更改了大小 [英] Python RuntimeError: dictionary changed size during iteration

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

问题描述

我正在练习一个非常简单的python代码。我试图找到解决方案,但找不到。

I am practising a really easy python code. I have tried to find the solution of it, but couldn't find it.

def del_contacts():
for name, number in d1.items():
    if (del_name == name):
        del d1.name and print ("Contact deleted!")
else:
    print ("Contact does not exist")

z = input ("Do you wish to delete any of the number you added? ")
if z == 'yes':
    del_name = input ("Type the name of the contact you wish to delete")
    del_contacts()
else:
    print ("ok")

但这给了我< module>中的错误。 del_contacts()
,后跟
在del_contacts中输入名称,d1中的数字。items():RuntimeError:字典在迭代过程中更改大小

but this gives me error in <module> del_contacts() followed with in del_contacts for name, numbers in d1.items(): RuntimeError: dictionary changed size during iteration

经常遇到这样的问题。谁能告诉我为什么会发生此错误?是否已进行任何修复,以后我应该怎么做才能避免此类错误?

Have been facing such problem a lot. Can anyone please tell me WHY this error is happening? Any fix and what should I do in future to avoid such errors?

推荐答案

您正在对字典进行迭代时对其进行修改。
获取物品时只需创建字典副本

You are modifying the dictionary while iterating over it. Just create a copy of the dict when getting the items

def del_contacts():
    for name, number in d1.copy().items():
        if (del_name == name):
            del d1.name and print ("Contact deleted!")
        else:
            print ("Contact does not exist")

这篇关于Python RuntimeError:字典在迭代过程中更改了大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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