我有一个嵌套字典的代码,我想访问"助手"值,并将其追加。我怎么做呢?
gameData = {
"metadata": {
"dataVersion": "2",
"matchId": "NA1_4263873346",
"participants": [
"Sw_wTB5fzxXvyXeCovgcGhKNw4hLKzgcEvWFKzMqZWtfiJ7HtbxYOK6Nb7nBU5SR-B3bNt4Ay9bvjQ",
"-t2_OfuyZFaCdZJ1lvbbfRFgYS1FWZcGhIsqj-8m-SS9UZ9wFyYeWBiGkcMgNEl_geH5CF9tX4SAzQ",
"A-n0X4QWr8Jr0PISogZK3VpnIqqVbm87jchMYpTrUrhiSfeoxVCl8ImnJxaE_lg9pIAdxNgaFpkT7g"
]
},
"info": {
"gameVersion": "12.6.431.7988",
"mapId": 11,
"participants": [
{
"assists": 9,
"deaths": 5,
"kills": 1
},
{
"assists": 1,
"deaths": 3,
"kills": 1
},
{
"assists": 3,
"deaths": 5,
"kills": 6
}
]
}
我使用这个来循环遍历它们,但是它返回错误"TypeError:列表索引必须是整数或切片,而不是字符串"
participants = []
for row in gameData['metadata']['participants']:
participants_row = {}
participants_row['assists'] = gameData['info']['participants']['assists']
participants.append(participants_row)
谁能帮助我了解如何循环通过它来获得所需的值?
您在访问dict
部分时出现了几个错误。
我想你是这个意思:
# gameData = {"metadata": { ...
participants = []
for row in gameData['info']['participants']:
participants_row = {}
participants_row['assists'] = row['assists']
participants.append(participants_row)
print(participants)
您的原始:for row in gameData['metadata']['participants']:
在错误的participants
列表上迭代。你的意思是:for row in gameData['info']['participants']:
participants_row['assists'] = match_detail['info']['participants']['assists']
我假设是这行代码导致了错误。要调试它,请将其分解为更小的部分:
info = match_detail['info']
participants = info['participants']
assists = participants['assists']
如果这样做,您将看到第三行导致错误。所以添加
print(participants)
现在我们看到participants
是一个列表,但是你把它当作字典来使用。
我想你想从每个participant
中得到assists
。一种方法是使用列表推导式:
assists = [p['assists'] for p in participants]
注:
python团队正在改进错误消息,以便消息指向导致此类错误的特定索引。我不知道它会在哪个版本发布,但我很期待它,因为这种嵌套索引非常常见。