我的最终目标是从多级dictas seen in this tutorial创建一个pandas DataFrame
。但是,我收到一个KeyError,指出其中一个键不在dict中。下面是多级dict的一个子集:
{
"draftDetail": {
"drafted": True,
"inProgress": False
},
"gameId": 1,
"id": 862068,
"schedule": [
{
"away": {
"adjustment": 0.0,
"cumulativeScore": {
"losses": 0,
"statBySlot": NULL,
"ties": 0,
"wins": 0
},
"pointsByScoringPeriod": {
"1": 126.82
},
"teamId": 1,
"tiebreak": 0.0,
"totalPoints": 126.82
},
"home": {
"adjustment": 0.0,
"cumulativeScore": {
"losses": 0,
"statBySlot": NULL,
"ties": 0,
"wins": 0
},
"pointsByScoringPeriod": {
"1": 115.52
},
"teamId": 15,
"tiebreak": 0.0,
"totalPoints": 115.52
},
"id": 0,
"matchupPeriodId": 1,
"playoffTierType": "NULL",
"winner": "AWAY"
},
{
"away": {
"adjustment": 0.0,
"cumulativeScore": {
"losses": 0,
"statBySlot": NULL,
"ties": 0,
"wins": 0
},
"pointsByScoringPeriod": {
"1": 183.4
},
"teamId": 16,
"tiebreak": 0.0,
"totalPoints": 183.4
},
"home": {
"adjustment": 0.0,
"cumulativeScore": {
"losses": 0,
"statBySlot": NULL,
"ties": 0,
"wins": 0
},
"pointsByScoringPeriod": {
"1": 115.08
},
"teamId": 6,
"tiebreak": 0.0,
"totalPoints": 115.08
},
"id": 1,
"matchupPeriodId": 1,
"playoffTierType": "NULL",
"winner": "AWAY"
}
]
}
然后,要创建df,我使用以下代码:
df = [[
game['matchupPeriodId'],
game['home']['teamId'], game['home']['totalPoints'],
game['away']['teamId'], game['away']['totalPoints']
] for game in d['schedule']]
df = pd.DataFrame(df, columns=['Week', 'Team1', 'Score1', 'Team2', 'Score2', 'PlayoffTier'])
df.head()
但是,我得到了这个错误:
Traceback (most recent call last):
File "<ipython-input-65-adda3411722d>", line 5, in <module>
] for game in d['schedule']]
File "<ipython-input-65-adda3411722d>", line 5, in <listcomp>
] for game in d['schedule']]
KeyError: 'away'
我还尝试查看是否可以使用以下方法在dict中识别钥匙:
if 'away' in d['schedule']:
print('will execute')
else:
print('wont execute')
它不会执行
有没有关于如何修复错误的建议?为了进一步了解上下文,我连接到ESPN的FantasyFootball API以最初检索数据,并可以共享错误之前的代码
提前谢谢
当没有“离开”键时,您必须处理要做的事情。这是因为季后赛中有两支球队需要告别:
输出:
相关问题 更多 >
编程相关推荐