在dict中解析数据

时间:2018-05-21 01:35:48

标签: python json string python-2.7 dictionary

我有一个dict,我试图从中获取某些数据,这个dict的例子如下:

{
    'totalGames': 1,
    'dates': [{
        'totalGames': 1,
        'totalMatches': 0,
        'matches': [],
        'totalEvents': 0,
        'totalItems': 1,
        'games': [{
            'status': {
                'codedGameState': '7',
                'abstractGameState': 'Final',
                'startTimeTBD': False,
                'detailedState': 'Final',
                'statusCode': '7',
                },
            'season': '20172018',
            'gameDate': '2018-05-20T19:00:00Z',
            'venue': {'link': '/api/v1/venues/null',
                       'name': 'Bell MTS Place'},
            'gameType': 'P',
            'teams': {'home': {'leagueRecord': {'wins': 9,
                       'losses': 8, 'type': 'league'}, 'score': 1,
                       'team': {'link': '/api/v1/teams/52',
                       'id': 52, 'name': 'Winnipeg Jets'}},
                       'away': {'leagueRecord': {'wins': 12,
                       'losses': 3, 'type': 'league'}, 'score': 2,
                       'team': {'link': '/api/v1/teams/54',
                       'id': 54, 'name': 'Vegas Golden Knights'}}},
            'content': {'link': '/api/v1/game/2017030325/content'},
            'link': '/api/v1/game/2017030325/feed/live',
            'gamePk': 2017030325,
            }],
        'date': '2018-05-20',
        'events': [],
        }],
    'totalMatches': 0,
    'copyright': 'NHL and the NHL Shield are registered trademarks of the National Hockey League. NHL and NHL team marks are the property of the NHL and its teams. \xa9 NHL 2018. All Rights Reserved.',
    'totalEvents': 0,
    'totalItems': 1,
    'wait': 10,
    }

我有兴趣获得某个团队的得分,如果他们当晚玩,例如,如果我感兴趣的团队是Vegas Golden Knights我想创建一个包含他们得分的变量(在这种情况下为2)。我完全坚持这一点,所以任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

这只会变成难看的解析,但很容易遵循JSON结构;会建议为您的目的压扁结构。话虽如此,如果您想在特定日期找到特定团队的分数,您可以这样做:

def find_score_by_team(gamedict, team_of_interest, date_of_interest):
    for date in gamedict['dates']:
        for game in date['games']:
            if game['gameDate'].startswith(date_of_interest):
                for advantage in game['teams']:
                    if game['teams'][advantage]['team']['name'] == team_of_interest:
                        return game['teams'][advantage]['score']
    return -1

示例查询:

>>> d = {'totalGames':1,'dates':[{'totalGames':1,'totalMatches':0,'matches':[],'totalEvents':0,'totalItems':1,'games':[{'status':{'codedGameState':'7','abstractGameState':'Final','startTimeTBD':False,'detailedState':'Final','statusCode':'7',},'season':'20172018','gameDate':'2018-05-20T19:00:00Z','venue':{'link':'/api/v1/venues/null','name':'BellMTSPlace'},'gameType':'P','teams':{'home':{'leagueRecord':{'wins':9,'losses':8,'type':'league'},'score':1,'team':{'link':'/api/v1/teams/52','id':52,'name':'WinnipegJets'}},'away':{'leagueRecord':{'wins':12,'losses':3,'type':'league'},'score':2,'team':{'link':'/api/v1/teams/54','id':54,'name':'VegasGoldenKnights'}}},'content':{'link':'/api/v1/game/2017030325/content'},'link':'/api/v1/game/2017030325/feed/live','gamePk':2017030325,}],'date':u'2018-05-20','events':[],}],'totalMatches':0,'copyright':'NHLandtheNHLShieldareregisteredtrademarksoftheNationalHockeyLeague.NHLandNHLteammarksarethepropertyoftheNHLanditsteams.\xa9NHL2018.AllRightsReserved.','totalEvents':0,'totalItems':1,'wait':10,}
>>> find_score_by_team(d, 'VegasGoldenKnights', '2018-05-20')
2

如果球队当晚没有参加比赛,则返回-1,否则返回球队的得分。