我正在练习一个非常简单的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
已经遇到很多这样的问题了。谁能告诉我为什么会发生这个错误?有什么修复方法以及将来我应该做什么以避免此类错误?
您在迭代字典时正在修改它。
只需在获取项目时创建字典的副本
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")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)