Python请求将列表转换为字典

2024-09-26 17:55:32 发布

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

我尝试使用python从thebluealliance.com网站. 这是我第一次尝试这样做,我成功地从网站上获得了一些数据,但这不是我所需要的。请求.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

^{pr2}$

Tags: 数据字符串代码comjson列表data字典
1条回答
网友
1楼 · 发布于 2024-09-26 17:55:32

从它的外观来看,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'])

输出是

^{pr2}$

或者使用列表理解

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

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

相关问题 更多 >

    热门问题