在此示例中,我希望使用NBA API收集特定数据,我试图从规范化的字典中检索随机球员的全名和身高
from nba_api.stats.static import players
from nba_api.stats.endpoints import commonplayerinfo
import random
def activePlayers():
# Gets a random active player.
playerList = players.get_active_players()
random.shuffle(playerList)
playerList = playerList.pop()
# Gets random active players info
player_info = commonplayerinfo.CommonPlayerInfo(player_id=playerList['id'])
player_info = player_info.get_normalized_dict()
print('FULL_NAME: {}\nHEIGHT: {}'.format(player_info.get('DISPLAY_FIRST_LAST'), player_info.get('HEIGHT')))
activePlayers()
如果我将打印更改为print(player_info),则打印内容为:
{'CommonPlayerInfo': [{'PERSON_ID': 202339, 'FIRST_NAME': 'Eric', 'LAST_NAME': 'Bledsoe', 'DISPLAY_FIRST_LAST': 'Eric Bledsoe', 'DISPLAY_LAST_COMMA_FIRST': 'Bledsoe, Eric', 'DISPLAY_FI_LAST': 'E. Bledsoe', 'BIRTHDATE': '1989-12-09T00:00:00', 'SCHOOL': 'Kentucky', 'COUNTRY': 'USA', 'LAST_AFFILIATION': 'Kentucky/USA', 'HEIGHT': '6-1', 'WEIGHT': '205', 'SEASON_EXP': 9, 'JERSEY': '6', 'POSITION': 'Guard', 'ROSTERSTATUS': 'Active', 'TEAM_ID': 1610612749, 'TEAM_NAME': 'Bucks', 'TEAM_ABBREVIATION': 'MIL', 'TEAM_CODE': 'bucks', 'TEAM_CITY': 'Milwaukee', 'PLAYERCODE': 'eric_bledsoe', 'FROM_YEAR': 2010, 'TO_YEAR': 2019, 'DLEAGUE_FLAG': 'Y', 'NBA_FLAG': 'Y', 'GAMES_PLAYED_FLAG': 'Y', 'DRAFT_YEAR': '2010', 'DRAFT_ROUND': '1', 'DRAFT_NUMBER': '18'}], 'PlayerHeadlineStats': [{'PLAYER_ID': 202339, 'PLAYER_NAME': 'Eric Bledsoe', 'TimeFrame': '2018-19', 'PTS': 15.9, 'AST': 5.5, 'REB': 4.6, 'PIE': 0.125}], 'AvailableSeasons': [{'SEASON_ID': '12010'}, {'SEASON_ID': '22010'}, {'SEASON_ID': '22011'}, {'SEASON_ID': '42011'}, {'SEASON_ID': '12012'}, {'SEASON_ID': '22012'}, {'SEASON_ID': '42012'}, {'SEASON_ID': '12013'}, {'SEASON_ID': '22013'}, {'SEASON_ID': '12014'}, {'SEASON_ID': '22014'}, {'SEASON_ID': '12015'}, {'SEASON_ID': '22015'}, {'SEASON_ID': '12016'}, {'SEASON_ID': '22016'}, {'SEASON_ID': '12017'}, {'SEASON_ID': '22017'}, {'SEASON_ID': '42017'}, {'SEASON_ID': '12018'}, {'SEASON_ID': '22018'}, {'SEASON_ID': '42018'}]}
我得到的是:
FULL_NAME: None
HEIGHT: None
我的期望:
FULL_NAME: Eric Bledsoe
HEIGHT: 6-1
最佳答案
您的player_info
是具有形状的字典
{
'CommonPlayerInfo': [ ... ],
'PlayerHeadlineStats': [ ... ],
'AvailableSeasons': [ ...]
}
您打算使用的字典是
'CommonPlayerInfo'
寻址的列表的第一个元素。因此,如果您添加以下行player_info = player_info.get('CommonPlayerInfo')[0]
在
print
语句之前,您应该得到想要的东西。PS:在所有球员中,真的必须是埃里克·布莱索吗?凭空想像力都不是我的最爱。