需要使用python从api响应返回一个键的所有值



我试图从api响应中列出国家的值。当我累了,它抛出一个错误作为TypeError:列表索引必须是整数或切片,而不是str

import requests
response = requests.get("https://countriesnow.space/api/v0.1/countries")
json_response = response.json()
# dictionary = json.dumps(response.json(), sort_keys = True, indent = 4)
country_name = json_response['data']['country']

我已经从浏览器中获取了api端点,我需要列出国家值,并检查我作为文本提取的数据是否与api端点中存在的国家值相匹配。

你能让我知道我在哪里使用做错误,因为我被困在这个过去的两天。

当我给它

country_name = json_response['data'][0]['country']

将打印第一个国家名称,但我需要country的所有值。

遍历数据列表项,选择键为country的值并追加到列表

countries = []
for country in json_response['data']:
countries.append(country['country'])
print(countries)

另一个使用列表推导式的方法:

countries = [json_response['data'][i]['country'] for i in range(len(json_response['data']))]

你需要遍历列表json_response['data']中的所有内容并取出country:

countries = [json_response['data'][i]['country'] for i in len(json_response['data'])]

您的响应数据是一个嵌套列表。您需要遍历它以检索所有值:

countries = [x['country'] for x in json_response['data']]
# or
countries = list(map(lambda x: x['country'], json_response['data']))

country_name = json_response['data']['country']破裂的原因是json_response['data']给你一个list,它只能由int或数字索引,因此错误TypeError: list indices must be integers or slices, not str

这里有一个更简单的版本

countries = []
for country in json_response["data"]:
countries.append(country["country"])
print(countries)

相关内容

最新更新