python - 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},
...]
解决方案
从外观上看,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']
推荐阅读
- ios - 为什么其中一个动画没有激活?
- sequelize.js - 续集 findAll 方法,除了
- python - 在 SQL Server 中加密并在 Python / spark 中解密
- html - Bootstrap:是否可以在这样的列中包含行?
- reactjs - useDebounce 测试有时会失败,但有时不会
- c# - 无法使用 c# 订阅 WebSocket 上的特定频道
- selenium - 我如何通过 Selenium 进行操作:我的 Gmail 有两步身份验证,所以我想使用我的应用密码登录我的 gmail。我该如何使用 WebDriver?
- angular - 无法在订阅的组件视图中使用响应,有什么替代方法?
- url - 如何使“URL 协议”从其自己的目录启动应用程序,而不是从 c:\windows\system32 启动?
- pandas - 使用连接键在修改/删除列表中查找第一次出现的记录