[英]Python - Dict nest in List nested in Dict
When I do requests.get I'm given back a response that looks like this, the data is from the LoL API:当我执行 requests.get 时,我得到了一个看起来像这样的响应,数据来自 LoL API:
{
"champions": [
{
"id": 111,
"stats": {
"maxChampionsKilled": 2,
"maxNumDeaths": 5,
"mostChampionKillsPerSession": 2,
"mostSpellsCast": 0,
"totalAssists": 25,
"totalChampionKills": 2,
"totalDamageDealt": 40838,
"totalDamageTaken": 27900,
"totalDeathsPerSession": 5,
"totalDoubleKills": 0,
"totalFirstBlood": 0,
"totalGoldEarned": 11070,
"totalMagicDamageDealt": 21083,
"totalMinionKills": 56,
"totalPentaKills": 0,
"totalPhysicalDamageDealt": 12876,
"totalQuadraKills": 0,
"totalSessionsLost": 1,
"totalSessionsPlayed": 1,
"totalSessionsWon": 0,
"totalTripleKills": 0,
"totalTurretsKilled": 1,
"totalUnrealKills": 0
}
},
I'm struggling getting the data that is inside of "stats."我正在努力获取“统计数据”中的数据。 What I really want to do is is something similar to the following:我真正想做的是类似于以下内容:
champ_data = received['champions']['stats']['totalSessionsPlayed']
print(champ_data)
However it isn't working because after "champions" there is a '[' and I get the error:但是它不起作用,因为在“冠军”之后有一个 '[' 并且我收到错误:
TypeError: list indices must be integers, not str
You want this你要这个
received['champions'][0]['stats']
for the first champion's stats.对于第一个冠军的统计数据。 Or, this或这个
received['champions'][n]['stats']
for the nth champion's stats.第n个冠军的数据。 Or, this或这个
[champion['stats'] for champion in received['champions']]
for a list of each champion's stats.获取每个冠军的统计数据列表。
received['champions']
is a list. received['champions']
是一个列表。 To process all entries (if that's what you want to do) you have to iterate it:要处理所有条目(如果这是您想要做的),您必须对其进行迭代:
for champion in received['champions']:
print(champion['stats']['totalSessionsPlayed'])
此外,如果属性champions
为空,请对您收到的数据对象进行一些检查。
In your example 'champion' is a list with one element.在您的示例中,“冠军”是一个包含一个元素的列表。 This list element can be accessed by champion[0].这个列表元素可以被冠军[0]访问。 This list's element is a dictionary with 2 key:value pairs.这个列表的元素是一个有 2 个键值对的字典。 'stats' is a key of 2nd pair which can be accessed by champion[0]['stats']. 'stats' 是第二对的键,可以通过 Champion[0]['stats'] 访问。 Again the value of 'stats' key is a dictionary, whose any key's value eg value of 'totalSessionsPlayed' can be accessed by champion[0]['stats']['totalSessionsPlayed']同样,'stats' 键的值是一个字典,其任何键的值,例如 'totalSessionsPlayed' 的值都可以被冠军 [0]['stats']['totalSessionsPlayed'] 访问
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.