尝试将嵌套的json数据提取到垂直列表中

2024-10-03 09:08:06 发布

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

如何从该url提取所有储罐名称 (https://api.wotblitz.com/wotb/encyclopedia/vehicles/?application_id=e079b7fe335c9af4749be776fbf5fc2b&nation=usa) 并将它们显示为垂直列表

仅供参考,为了解决这个问题,我在过去的40个小时里开始编写代码。我知道正确的解决方案是从一个为期6个月的python速成班开始,但我真的想通过解决这个问题来学习。任何建议的代码都将不胜感激。 谢谢,


Tags: 代码https名称comapiidurlapplication
2条回答

这里有一个建议,使用“列表理解”从坦克列表中提取名称

import requests

response = requests.get('https://api.wotblitz.com/wotb/encyclopedia/vehicles/?application_id=e079b7fe335c9af4749be776fbf5fc2b&nation=usa')
j = response.json()

tanks = j['data'].values()
names = [tank['name'] for tank in tanks]  # list comprehension

print(names)

这段代码可以做到这一点。由于您是初学者,我将添加一些注释,试图解释代码的作用。 您还可以进一步检查以下概念:

  • RESTAPI
  • Python请求模块
  • Python数据结构(这里主要使用字典)

示例代码:

import requests # library to interact with HTTP

# Get the data
response = requests.get('https://api.wotblitz.com/wotb/encyclopedia/vehicles/?application_id=e079b7fe335c9af4749be776fbf5fc2b&nation=usa')
# Transform the reponse in python dictionary
data_from_api = response.json()

# Get only the part of data for which we care
tanks = data_from_api.get("data")

tank_names = [] # initialize empty list

# Tanks are now a dictionary as well.
# we want to get all the keys and all the values from them
# and from the values (also dictionaries) we want to extract the name value
for tank, specs in tanks.items():
    
    tank_names.append(specs.get("name"))
print(tank_names)

相关问题 更多 >