I am trying to list the values of country from the api response. While I tired it is throwing an error as TypeError: list indices must be integers or slices, not 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']
I have taken the api endpoint from the browser where i need to list out the country values and check whether the data i extracted as text matches the country values present in the api endpoint.
Can you please let me know where I am using doing the mistake, as i was stuck on this for past wo days.
When I give it as
country_name = json_response['data'][0]['country']
the first country name is getting printed but i need all the values of country.
CodePudding user response:
Loop through the data list items and pick the value with key country
and append to the list
countries = []
for country in json_response['data']:
countries.append(country['country'])
print(countries)
Another method using list comprehension:
countries = [json_response['data'][i]['country'] for i in range(len(json_response['data']))]
CodePudding user response:
You need to iterate over everything in the list json_response['data']
and pull out country
:
countries = [json_response['data'][i]['country'] for i in len(json_response['data'])]
CodePudding user response:
Your response data is a nested list. You need to loop through it to retrieve all values:
countries = [x['country'] for x in json_response['data']]
# or
countries = list(map(lambda x: x['country'], json_response['data']))
CodePudding user response:
The reason why country_name = json_response['data']['country']
breaks is that json_response['data']
gives you a list
which can only be indexed by int
or numbers hence the error TypeError: list indices must be integers or slices, not str
.
here is a much simpler version of what they're trying to do
countries = []
for country in json_response["data"]:
countries.append(country["country"])
print(countries)