如何从字典列表中的字典键中获取所有值

2024-05-16 12:20:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一本字典,看起来像这样:

response = {
     'name': "ExampleName",
     'tier': 'Master',
     'queue': 'RANKED_SOLO_5x5',
     'entries': [
          {
         'playerOrTeamId': '35417098',
         'playerOrTeamName': 'ExamplePlayerName',
         'wins': 205,
         'losses': 185
         },
         {
         'playerOrTeamId': '22877699',
         'playerOrTeamName': 'ExamplePlayerName2',
         'division': 'I',
         'leaguePoints': 80,
         'wins': 300,
         'losses': 272
          }
      ]
}

等等。现在我想print所有的playerOrTeamId's 我已经试过了:

print(response['entries']['playerOrTeamId'])

这给了我一个错误:

TypeError: list indices must be integers or slices, not str

但如果我试着举个例子:

print(response['entries'][0]['playerOrTeamId'])

它只给我第一个的playerOrTeamId。你知道吗


Tags: namemaster字典queueresponsesolotierentries
1条回答
网友
1楼 · 发布于 2024-05-16 12:20:58

可以使用list comprehension从响应中检索所有id。你知道吗

all_ids = [entry["playerOrTeamId"] for entry in response["entries"]]

这是花哨的Python速记,用于循环遍历响应并创建一个id列表。你知道吗

相关问题 更多 >