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

为何使用dict.get()仍出现KeyError?按文档说明这不应发生

问题原因与解决方法

错误根源

你误解了get()方法的作用范围:get()确实不会抛出KeyError,但你的错误出在调用get()之前的索引访问上。

当某场比赛没有指定probablePitcher时,game['teams']['home']['probablePitcher']这一步是直接用索引访问不存在的键,这会直接触发KeyError——此时代码还没走到调用get('fullName')的环节,所以你给get()加默认值也没用。

解决办法

把索引访问替换成get()方法,给中间层级的键设置默认空字典,确保即使某个键不存在,后续的get()调用也能安全执行:

import requests    
url = f'https://statsapi.mlb.com/api/v1/schedule?sportId=1&hydrate=probablePitcher&date={2023-06-28}'
response = requests.get(url)
games = response.json()['dates'][0]['games']
for game in games:
    # 先获取home对象,再用get获取probablePitcher,默认返回空字典
    prob_pitcher = game['teams']['home'].get('probablePitcher', {})
    # 再从prob_pitcher中获取fullName,不存在则返回None
    prob_home = prob_pitcher.get('fullName')

或者用更简洁的嵌套写法:

prob_home = game['teams']['home'].get('probablePitcher', {}).get('fullName')

如果想更严谨(防止teams或home也意外不存在),可以把所有层级都换成get():

prob_home = game.get('teams', {}).get('home', {}).get('probablePitcher', {}).get('fullName')

这样无论中间哪个键缺失,代码都不会抛出KeyError,而是返回None(或你指定的默认值)。

内容的提问来源于stack exchange,提问作者Peter Ohaver

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.18 00:22:07