I am struggling when trying to iterate through a large list of dictionaries. For the most part they contain the same keys, but there are a few that are missing some keys. Obviously this causes error and I'm unable to successfully run. Below is a sample of the list:
test_dict = [{'away': {'gamesPlayed': 0,
'pointsByScoringPeriod': {'14': 84.54},
'teamId': 9,
'tiebreak': 0.0,
'totalPoints': 84.54},
'home': {'gamesPlayed': 0,
'pointsByScoringPeriod': {'14': 84.54},
'teamId': 9,
'tiebreak': 0.0,
'totalPoints': 84.54},
'id': 98,
'matchupPeriodId': 14,
'playoffTierType': 'NONE',
'winner': 'AWAY'},
{'home': {'gamesPlayed': 0,
'pointsByScoringPeriod': {'14': 84.54},
'teamId': 9,
'tiebreak': 0.0,
'totalPoints': 84.54},
'id': 98,
'matchupPeriodId': 14,
'playoffTierType': 'NONE',
'winner': 'AWAY'}]
We are missing away
in the second dictionary, so when I run the following code:
matchup_data = []
for matchup in test_dict:
Week = matchup['matchupPeriodId']
Matchup_ID = matchup['id']
Winner = matchup['winner']
Game_Type = matchup['playoffTierType']
Away_ID = matchup['away']['teamId']
Away_Points = matchup['away']['totalPoints']
Home_ID = matchup['home']['teamId']
Home_Points = matchup['home']['totalPoints']
matchup_data.append([
Week, Matchup_ID, Winner, Game_Type, Away_ID, Away_Points, Home_ID, Home_Points
])
I obviously get the error KeyError: 'away'
since away
is nowhere to be found in the second dictionary.
Is there a way to ignore the missing keys and just put a NULL
in place of the variables for the dictionaries where away
is missing? Thank you in advance.
Finally, if this has already been asked I apologize as I cannot seem to find it anywhere. I see multiple questions regarding iterating through dictionaries but none regarding different keys
CodePudding user response:
Replace:
matchup['away']['teamId']
with:
matchup['away']['teamId'] if 'away' in matchup else None
You can also use chained calls to .get
, with each call supplying an appropriate default:
matchup.get('away', {}).get('teamId', None)