Python RuntimeError:字典在迭代期间改变了大小

时间:2015-11-12 19:28:15

标签: python dictionary

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

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")

但是这给了我错误in <module> del_contacts() 接着是 in del_contacts for name, numbers in d1.items(): RuntimeError: dictionary changed size during iteration

一直面临着这样的问题。任何人都可以告诉我为什么会发生这种错误?任何修复以及我将来应该做些什么来避免这样的错误?

1 个答案:

答案 0 :(得分:7)

您正在迭代它时修改字典。 只需在获取项目时创建一个dict副本

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")