Python请求将列表转换为字典

时间:2019-05-10 16:47:01

标签: python json python-requests

我正在尝试使用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}, 
...]

1 个答案:

答案 0 :(得分:0)

从外观上看,import { AngularFireModule } from 'angularfire2'; import { AngularFirestoreModule } from 'angularfire2/firestore'; import { firebaseConfig } from './credentials'; 是词典的列表,因此您需要遍历该列表以将数据提取到字典中

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)