Python 字典 - 读取键时出错

标签 python dictionary

我正在弄乱字典,以前从未遇到过问题。我编写了一些循环来帮助匹配和清理字典,但我不断收到以下错误。

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=1j=1)中,您删除了 resultDict["image1"] 和下一个循环( i=1j=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/

相关文章:

Python Pandas : creating a dataframe using a function for one of the fields

Python:在列表字典中对列表进行排序,其中一个列表是排序的关键

php - 在列表中分组 - php

python - PyPy 文件附加模式

python - 连接 2 个具有 54 个条目的数据帧产生 1 行

python - MultiValueDictKeyError : GET works, POST 没有。为什么?

Python 删除不出现在单独字典中的字典键

c++ - < 遍历 C++ 映射时缺少运算符

python - 如何在模型级别分页数据(django)

python - 插件无法在 MusicBrainz v1.2 上运行