I tried to get weather details using Open Weather Map APIs which worked till a point. I want to find the description of the clouds (scattered, heavy etc) and I am getting a keyword error which I am unable to correct
This is the code I have written-
import requests , json
apiKey = "d5f6e96071109af97ee3b206fe8cb0cb"
baseURL = "https://api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}"
cityName = "ranchi"
completeURL = f"https://api.openweathermap.org/data/2.5/weather?q={cityName}&appid={apiKey}"
response = requests.get(completeURL)
data = response.json()
print(data)
print("Minimum Temperature ",data["main"]["temp_min"])
print("Maximum Temperature ",data["main"]["temp_max"])
print("Temperature ",data["main"]["pressure"])
print("Visibility ",data["visibility"])
print("Humidity ",data["main"]["humidity"])
print("Clouds ",data["weather"]["description"])
This is the error (of the last print statement) I am getting-
line 23, in <module>
print("Clouds ",data["weather"]["description"])
TypeError: list indices must be integers or slices, not str
What is the keyword I am missing ?
CodePudding user response:
For reference, this is an excerpt of the output of the API call:
"coord": {
"lon": 85.3333,
"lat": 23.35
},
"weather": [{
"id": 802,
"main": "Clouds",
"description": "scattered clouds"
}],
"main": {
"temp": 312.21,
"feels_like": 310.96
....
If you look closely, you will notice that, for example, main
directly references a json object. So you can refer to data["main"]["humidity"]
and expect it to work. However, weather
references a list, not a json object. So referring to it as data["weather"]["description"]
will assume that description
is the index of the weather list.
To solve the issue, you only need to provide the index first (0 in this case) like so:
data["weather"][0]["description"]
And everything should work as expected.
CodePudding user response:
Keeping all same except data["weather"][0]["description"] because the "weather" key has a list of values from which you have to get a "description".
I Hope, it solves your problem!
import requests , json
apiKey = "d5f6e96071109af97ee3b206fe8cb0cb"
baseURL = "https://api.openweathermap.org/data/2.5/weather?q={city name}&appid={API key}"
cityName = "ranchi"
completeURL = f"https://api.openweathermap.org/data/2.5/weather?q={cityName}&appid={apiKey}"
response = requests.get(completeURL)
data = response.json()
print(data)
print("Minimum Temperature ",data["main"]["temp_min"])
print("Maximum Temperature ",data["main"]["temp_max"])
print("Temperature ",data["main"]["pressure"])
print("Visibility ",data["visibility"])
print("Humidity ",data["main"]["humidity"])
print("Clouds ",data["weather"][0]["description"])