我正在弄乱字典,以前从未遇到过问题。我编写了一些循环来帮助匹配和清理字典,但我不断收到以下错误。
Traceback (most recent call last):
File "C:/Users/Service02/Desktop/D/TT/test.py", line 10, in <module>
if resultDict[currentImageTest] == oldDict["image" + str(j)]:
KeyError: 'image1'
不知道为什么会出现明显的关键错误。使困惑。如有任何帮助,我们将不胜感激!
resultDict = {"image1":1, "image2":2, "image3":3, "image4":4, "image5": 5}
oldDict = {"image1":1, "image2":22, "image3":3, "image4":47, "image5": 5}
i=1
j=1
while i<6:
currentImageTest = "image" + str(i)
while j<6:
if resultDict[currentImageTest] == oldDict["image" + str(j)]:
del resultDict[currentImageTest]
else:
pass
j+=1
i+=1
print resultDict
最终结果(已解决):
i=1
while i<6:
currentImageTest = "image" + str(i)
j=1
while j<6:
if oldDict["image" + str(j)] == resultDict[currentImageTest]:
del resultDict[currentImageTest]
break
else:
pass
j+=1
i+=1
print resultDict
最佳答案
if resultDict[currentImageTest] == oldDict["image" + str(j)]:
del resultDict[currentImageTest]
在第一个循环(i=1
和 j=1
)中,您删除了 resultDict["image1"]
和下一个循环( i=1
和 j=2
)您尝试将 resultDict["image1"]
与 oldDict["image2"进行比较]
,但由于 resultDict["image1"]
已被删除,因此找不到 key
编辑:
最好使用 for
循环和 range()
而不是 while :
resultDict = {"image1":1, "image2":2, "image3":3, "image4":4, "image5": 5}
oldDict = {"image1":1, "image2":22, "image3":3, "image4":47, "image5": 5}
for i in range(1,6):
currentImageTest = "image" + str(i)
for j in range(1,6):
if resultDict[currentImageTest] == oldDict["image" + str(j)]:
del resultDict[currentImageTest]
break
else:
pass
关于Python 字典 - 读取键时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12168314/