处理一个KeyError最佳实践

时间:2018-06-08 14:36:22

标签: python python-3.x keyerror

我缩短了脚本和pendulum的开始日期,以便更快地重现此错误。如果开始日期为2016, 4, 2,则在KeyError发生之前,我已经获得了大约47,661个返回的结果。据我所知,我可以使用try: except来传递KeyError。但是我不会知道在那之后可能出现的任何其他关键错误,这似乎我只是(因为没有更好的词)"吞咽"我的错误。到目前为止,在万分之一(迄今为止)中出现这种情况的最佳做法是什么。

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)

1 个答案:

答案 0 :(得分:2)

最好的办法是在词典上使用.get方法。因此,请使用keys['about']而不是keys.get("about", "DEFAULT_VALUE")  所以,如果key存在,你将获得值,否则你将获得默认值,这是get方法中的第二个参数