python - 处理一个 KeyError 最佳实践
问题描述
我缩短了脚本和开始日期,pendulum
以便更快地重现此错误。在开始日期之前,2016, 4, 2
我收到了大约 47,661 个返回结果KeyError
。据我所知,我可以使用 atry:
except
来传递KeyError
. 但是,我不知道在那之后可能出现的任何其他 KeyErrors,而且我似乎只是(因为没有更好的词)“吞下”我的错误。50,000 次(到目前为止)发生中 1 次的最佳实践是什么。
import csv
import requests
import datetime
from pprint import pprint
import pendulum
gamepks = set()
start = pendulum.datetime(2016, 5, 18)
end = pendulum.datetime(2016, 10, 2)
period = pendulum.period(start, end)
for dt in period.range('days'):
day = dt.format('DD')
month = dt.format('MM')
year = dt.format('YYYY')
the_date = str(month) + "/" + str(day) + "/" + str(year)
try:
req = requests.get('http://gd.mlb.com/components/game/mlb/year_' + str(year) + '/month_' + str(month) + '/day_' + str(day) + '/miniscoreboard.json') #
get_gameIds = req.json()['data']['games']['game']
for gameId in get_gameIds:
gamepk = gameId['game_pk']
gamepks.add(gamepk)
except(KeyError,TypeError):
pass
for new_pk in sorted(gamepks):
req = requests.get('https://statsapi.mlb.com/api/v1.1/game/' + str(new_pk) + '/feed/live?language=en') # ' + str(gamepk) + ' 530302
at_bat_log = req.json()['liveData']['plays']['allPlays']
# Get Game date
game_data = req.json()['gameData']
gamedate = game_data['datetime']['originalDate']
# GET PARK & TEAMS
teams = game_data['teams']
home_team = teams['home']
park = home_team['abbreviation']
away = teams['away']['abbreviation']
home = home_team['abbreviation']
batter_team = (away,home)
pitcher_team = (home,away)
for keys in at_bat_log:
result = keys['result']
res_type = result['type']
res_event = result['event']
des = result['description']
rbi = result['rbi']
about = keys['about']
topbot = about['halfInning']
if topbot == "bottom":
topbot = "B"
if topbot == "top":
topbot = "T"
# Traceback (most recent call last):
# File "C:/Python36/Projects/Shoretend_for_testing_CODE.py", line 65, in <module>
# inn = about['inning']
# KeyError: 'inning'
inn = about['inning']
inning = str(topbot) + str(inn)
row = [new_pk, inning]
print(row)
解决方案
你最好的办法是.get
在字典上使用方法。所以,不要做keys['about']
,使用 keys.get("about", "DEFAULT_VALUE")
.
因此,如果键存在,您将获得该值,否则您将获得默认值,这是 get 方法中的第二个参数
推荐阅读
- php - 尝试将 sql 结果作为 json 数据类型回显时出现语法错误
- python - python:如何直接从字节字符串变量显示图像?
- amazon-web-services - 在 Postgres RDS 的克隆上运行 sql 迁移,然后将其用作主服务器
- google-forms - 希望我的谷歌表格向他们输入特定单元格的受访者电子邮件发送电子邮件
- java - Spring Shedlock 时间问题
- java - 将“费马素数测试”从 Java 转换为 Python 时出现问题
- variables - Ansible注册访问invocation_module?
- c# - 为什么 EF Core 两次提交一个事务?
- node.js - 如何填充数组的数组
- java - OOP原理和OOP概念的区别?