1

今まで問題にならなかった辞書をいじっています。次のエラーが発生し続けることを除いて、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
4

2 に答える 2

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

ここで、最初のループ(i=1j=1)で削除resultDict["image1"]し、次のループ(i=1j=2)で比較しようとしていますresultDict["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
于 2012-08-28T22:29:32.397 に答える
0

何が起こっているのかというと、存在しないキー、この場合は「image1」を参照しようとしているということです。KeyErrorに遭遇しないことを確認するために、チェックを使用する必要があります。

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

それかあなたはそれをtry..exceptで包むことができます

于 2012-08-28T22:30:16.317 に答える