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

Python统计奥运奖牌数出现KeyError的原因及解决方法

代码报错修复方案

错误根因

  • 触发KeyError: 'Norway'的直接原因是:当首次遇到没有录入medals_dict的国家时,你直接尝试访问medals_dict[full_country][medal],但此时medals_dict中还没有该国家对应的key,更不存在对应的二级奖牌计数字典,赋值操作直接访问不存在的key就会报错。
  • 你代码还存在第二个逻辑错误:if medal in full_country这行判断完全不符合需求,它是在检查奖牌类型字符串是否出现在国家名称字符串里,和你要统计对应奖牌数量的目标完全无关。

修复后代码

def total_medal_counter(year_in_data, full_country, medal):
    global year
    global medals_dict
    if year == year_in_data:
        # 国家已存在于统计字典中
        if full_country in medals_dict:
            # 对应奖牌类型已存在则计数+1,不存在则初始化为1
            if medal in medals_dict[full_country]:
                medals_dict[full_country][medal] += 1
            else:
                medals_dict[full_country][medal] = 1
            print(medals_dict)
        # 国家不存在于统计字典中,先初始化该国家的二级计数字典
        else:
            medals_dict[full_country] = {}
            medals_dict[full_country][medal] = 1
            print(medals_dict)

可选优化建议

尽量避免使用global声明全局变量,你可以把medals_dict和目标统计year作为参数传入函数,或者将统计结果作为返回值返回,降低代码耦合度,也更便于调试。

内容的提问来源于stack exchange,提问作者Sofiia Zinchenko

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 08:54:00