调用CricAPI获取球队名称时出现KeyError('teamInfo')问题求助
KeyError: 'teamInfo' 报错排查与解决方法
你在使用CricAPI开发实时板球比分应用时,遇到KeyError: 'teamInfo'报错——虽然部分返回数据包含teamInfo字段,但代码直接访问该字段时仍触发错误。
报错原因
CricAPI返回的data数组中,并非所有比赛条目都包含teamInfo字段。比如一些未开赛的赛事、小众赛事或特殊类型的比赛,可能缺失该字段。你的代码直接硬索引result["data"][match_number]["teamInfo"],遇到无该字段的条目就会抛出KeyError。
解决方法
需要在访问teamInfo前先做存在性校验,或者使用字典的get()方法安全取值。同时可以优化循环逻辑,让代码更简洁:
import requests api_key = "" url_currentmatches = f"https://api.cricapi.com/v1/cricScore?apikey={api_key}" response = requests.get(url_currentmatches) result = response.json() important_countries = ["Pakistan","New Zealand","Australia","Sri Lanka","South Africa","West Indies","England","India"] # 遍历所有比赛条目 for match in result["data"]: # 安全获取teamInfo字段,不存在则返回None team_info = match.get("teamInfo") # 跳过无有效球队数据的比赛 if not team_info or len(team_info) < 2: continue name1 = team_info[0]["name"] name2 = team_info[1]["name"] # 检查是否包含目标国家球队 for country in important_countries: if country in name1 or country in name2: print(f"name match: {name1} {name2}") print(f"We have the result: {name1} vs {name2}") print(country)
关键优化点
- 使用
match.get("teamInfo")替代直接索引,避免KeyError;若字段不存在,get()会返回None - 增加
len(team_info) < 2的判断,避免因球队数据不全导致后续索引报错 - 用
for match in result["data"]遍历比赛,比while循环更易读、更简洁 - 用
country in name1替代find(),代码更直观高效
内容的提问来源于stack exchange,提问作者Saif1708
相关产品推荐
相关产品推荐

