我正在尝试学习如何在python中操作数据。 我在txt文件中有以下数据
{"summonerId":000000,"games":[{"gameId":111111,"invalid":false,"gameMode":"CLASSIC","gameType":"MATCHED_GAME","subType":"NORMAL","mapId":11,"teamId":200,"championId":89,"spell1":3,"spell2":4,"level":30,"ipEarned":237,"createDate":1443314494341,"fellowPlayers":[{"summonerId":46350758,"teamId":100,"championId":157}],"stats":{"level":15,"goldEarned":10173,"numDeaths":5,"minionsKilled":48,"championsKilled":1,"goldSpent":9205,"totalDamageDealt":48752,"totalDamageTaken":23464,"team":200,"win":true,"largestMultiKill":1,"physicalDamageDealtPlayer":9064,"magicDamageDealtPlayer":35714,"physicalDamageTaken":18944,"magicDamageTaken":4005,"timePlayed":1831,"totalHeal":4129,"totalUnitsHealed":5,"assists":24,"item0":3401,"item1":2049,"item2":3117,"item3":3068,"item4":3075,"item5":1028,"item6":3340,"magicDamageDealtToChampions":9062,"physicalDamageDealtToChampions":3348,"totalDamageDealtToChampions":12411,"trueDamageDealtPlayer":3974,"trueDamageTaken":514,"wardKilled":1,"wardPlaced":16,"totalTimeCrowdControlDealt":104,"playerRole":2,"playerPosition":4}]}
我的最终目标是能够显示“统计数据”词典中的特定信息。
当我运行以下代码时
import json
matches = open('testdata.txt', 'r')
output = matches.read()
data=json.loads(output)
display = data["games"]
print("Info: " + str(display))
输出是与我所期望的“游戏”键相对应的所有内容。
当我尝试
时import json
matches = open('testdata.txt', 'r')
output = matches.read()
data=json.loads(output)
display = data["games"]["stats"]
print("Info: " + str(display))
我收到:TypeError: list indices must be integers, not str
我不确定如何继续,因为键明显是字符串而不是整数...
答案 0 :(得分:2)
您的data["games"]
值是列表;该列表中的每个元素都是一个字典,列表中的那些字典(可能)具有'stats'
键。列表可以包含0个或更多元素;在这种特殊情况下,只有1但可能有更多或没有。
循环遍历词典列表,或者使用索引从列表中选择特定词典。由于您的特定示例中只有一个,您可以使用0
索引索引该1个元素:
display = data["games"][0]["stats"]