Python词典 - 错误读取键

时间:2012-08-28 22:18:14

标签: python dictionary

我正在搞乱字典,我以前从来没有遇到过这个问题。我写了几个循环来帮助匹配和清除dict,除了我不断收到以下错误。

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

2 个答案:

答案 0 :(得分:1)

if resultDict[currentImageTest] == oldDict["image" + str(j)]:
            del resultDict[currentImageTest]

此处在第一个循环(i=1j=1)中,您删除了resultDict["image1"]以及您尝试比较的下一个循环(i=1j=2resultDict["image1"] oldDict["image2"]resultDict["image1"],但key已被删除,因此找不到for

编辑:

更好地使用range()循环和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 而不是在此处:

{{1}}

答案 1 :(得分:0)

正在发生的是您尝试引用不存在的密钥,在本例中为“image1”。您希望使用检查以确保不会遇到KeyError。

if resultDict.has_key(currentImageTest) and resultDict[currentImageTest] == oldDict["image" + str(j)]

或者你可以把它包装在try..except