繁体   English   中英

KeyError - 字典值/键

[英]KeyError - dictionary value/key

我循环遍历字典中的所有项目,使用语法: for key, value in questions.items() ,其中questions是字典名称。 这会将key指定为字典键,将value指定为字典值。

为什么我会收到以下错误?

line 13, in <module>
    ans = input("What is the capital of " + questions[value] + " ? ")
KeyError: 'y'
q1 = input("Please enter a country: ")
a1 = input("Please enter its capital: ")
q2 = input("Please enter a country: ")
a2 = input("Please enter its capital: ")

questions = {q1 : a1, q2 : a2}
score = 0
for key, value in questions.items():
    ans = input("What is the capital of " + questions[value] + " ? ")
    if ans == questions[key]:
        print("Correct!")
        score = score + 1
    else:
        print("Incorrect!!")

print("Final score is: ", score)

通过有意义地命名变量,您可以避免很多困惑。 例如,在你的循环中,你可以使用

for country, capital in questions.items():

当您只想使用大写字母时,您显然不会写ans = input("What is the capital of " + questions[capital] + "? ") 字典只有 map 一种方式:您只能检查一个国家作为关键字,而不是首都。 capital不是有效的密钥,因此要避免错误:

    ans = input(f"What is the capital of {country}? ")

使用字符串求和很好,但我认为 f-strings 更好,并且是自引入以来的实际约定。

迭代items的全部意义在于您不必重复查找:

    if ans == capital:
        print("Correct!")
        score = score + 1
    else:
        print("Incorrect!!")

它的原因是您正在使用dictionary.items()迭代字典,它返回键和值。

然后你试图通过值而不是键从字典中检索值。

for key, value in questions.items():
    ans = input("What is the capital of " + value + " ? ") # <-- Just use the value
    if ans == questions[key]:
        print("Correct!")
        score = score + 1
    else:
        print("Incorrect!!")

如果您想使用键来检索值,请使用questions[key]

但是我认为你正在尝试做的是问题是字典的关键,而答案是价值。

在那种情况下做ans = input("What is the capital of " + key + "? ")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM