Reputation: 101
I'm looking to collect specific data using an NBA API in this example I'm attempting to retrieve a random player's full name & height from a normalized dictionary
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()
If I were to change the print to print(player_info) this is what is printed:
{'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'}]}
What I get:
FULL_NAME: None
HEIGHT: None
What I expect:
FULL_NAME: Eric Bledsoe
HEIGHT: 6-1
Upvotes: 2
Views: 2433
Reputation: 56
Your player_info
is a dictionary with a shape
{
'CommonPlayerInfo': [ ... ],
'PlayerHeadlineStats': [ ... ],
'AvailableSeasons': [ ...]
}
The dictionary you intended to use instead is the first element of the list addressed by 'CommonPlayerInfo'
. Thus, if you add the following line
player_info = player_info.get('CommonPlayerInfo')[0]
before the print
statement, you should get what you are looking for.
PS: Of all players, did it really have to be Eric Bledsoe? Not a favorite player of mine by any stretch of imagination.
Upvotes: 4