【发布时间】:2020-06-22 18:47:33
【问题描述】:
我的最终目标是从多级字典 as seen in this tutorial 创建一个 pandas DataFrame。但是,我收到一个 KeyError 说明其中一个键不在字典中。这是多级字典的一个子集:
{
"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 的 Fantasy Football API 以初步检索数据,并且可以共享错误之前的代码。
提前致谢!
【问题讨论】:
-
(1) "d" 的打印表示在语法上不正确(缺少右括号)。 (2) 修复此问题后,显示的代码不会产生显示的错误。
-
嘿迈克尔,对不起,我复制并粘贴了字典的一个子集。如果它更有帮助,我可以包含整个字典,但它相当长。
-
最好不要。但是您可以在失败部分周围创建一个 try-except 块,将列表理解展开为正常的 for 循环,并在 except 部分打印
game的内容,以缩小导致失败的数据。
标签: python pandas dictionary