You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python遍历字典取值触发KeyError: 'y'报错原因排查

报错原因及修复方案

报错原因

你定义的questions字典结构为{国家名: 对应首都名},使用for key, value in questions.items()遍历时,已经直接获取到了每一组的键(国家名)和值(首都名)。
报错触发点在questions[value]这一步:value本身是首都名,并不是questions字典的键,用不存在的键去字典取值自然会抛出KeyError。
额外说明:后续判断逻辑中的questions[key]虽然不会触发报错,但属于多余操作,questions[key]的返回值就是你已经拿到的value,完全不需要二次查询字典。

修复方案

仅需要修改循环内的两行代码即可,调整后的完整代码如下:

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():
    # 直接用已经拿到的国家名key拼接问题
    ans = input("What is the capital of " + key + " ? ")
    # 直接和已经拿到的正确首都value比对即可
    if ans == value:
        print("Correct!")
        score = score + 1
    else:
        print("Incorrect!!")

print("Final score is: ", score)

内容的提问来源于stack exchange,提问作者xXx JOKER xXx

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 03:54:01