首页 > 解决方案 > Python 请求将列表转换为字典

问题描述

我正在尝试使用 python 从 thebluealliance.com 中提取数据。这是我第一次尝试这样做,并且我成功地从该站点获取了一些数据,但这不是我需要的。当我需要字典以便基于键进行解析时,Requests.json() 会为我返回一个列表。我将如何将其转换为字典?我目前收到一条错误消息,指出索引需要是整数,而不是字符串。

这是我用来获取数据的代码。

response = requests.get(TBA_URL + '/event/2019pncmp/teams/simple?X-TBA-Auth-Key=' + TBA_AUTH_KEY)
    data = response.json()
    print(data['city']) //Error is here.

示例data

[{'city': 'Issaquah', 'country': 'USA', 'key': 'frc1318', 
'name': 'The Boeing Company/State of Washington OSPI/Issaquah Schools Foundation&Issaquah High School', 
'nickname': 'Issaquah Robotics Society', 'state_prov': 'Washington', 
'team_number': 1318}, {'city': 'Wilsonville', 'country': 'USA', 
'key': 'frc1425', 'name': 'Lam Research/3D Systems/Xerox/DW Fritz/Rockwell Collins/TE Connectivity/Mentor Graphics/A-dec/City Of Wilsonville/Shields Manufacturing/Oregon Technology/Apex Plastics&Wilsonville High School', 
'nickname': 'Error Code Xero', 'state_prov': 'Oregon', 'team_number': 1425}, 
...]

标签: pythonjsonpython-requests

解决方案


从外观上看,data是一个字典列表,所以需要遍历列表来拉取字典中的数据

data=[{'city': 'Issaquah', 'country': 'USA', 'key': 'frc1318', 'name': 'The Boeing Company/State of Washington OSPI/Issaquah Schools Foundation&Issaquah High School', 'nickname': 'Issaquah Robotics Society', 'state_prov': 'Washington', 'team_number': 1318}, {'city': 'Wilsonville', 'country': 'USA', 'key': 'frc1425', 'name': 'Lam Research/3D Systems/Xerox/DW Fritz/Rockwell Collins/TE Connectivity/Mentor Graphics/A-dec/City Of Wilsonville/Shields Manufacturing/Oregon Technology/Apex Plastics&Wilsonville High School', 'nickname': 'Error Code Xero', 'state_prov': 'Oregon', 'team_number': 1425}]

#Iterate through the list and get value of city key from dictionary
for item in data:
    print(item['city'])

输出是

Issaquah
Wilsonville

或使用列表理解

res = [item['city'] for item in data]
print(res)

输出是['Issaquah', 'Wilsonville']


推荐阅读