I am trying to create a python program (as a university exercise) that will get coordinates from the user and print certain messages to the user eg: if it rains at the certain region it will print "I am singing the rain"
import json,urllib2
while True:
x=input("Give the longitude:")
if x<=180 and x>=-180:
x=str(x)
break
while True:
y=input("Give the latitude:")
if y<=90 and y>=-90:
y=str(y)
break
url="http://api.openweathermap.org/data/2.5/weather?lat="+y+"&lon="+x+"&appid=01e7a487b0c262921260c09b84bdb456"
weatherbot=urllib2.urlopen(url)
weatherinfo=weatherbot.read()
So far I can get the info from Openweathermap,but if I try to get specific info like that:
currentweather=weatherinfo["weather"]["main"]
It gives me this error message:
TypeError:string indices must be integer, not str
Despite when I do:
print weatherinfo
it appears to be a dictionary.
Can someone explain to me what I am doing wrong?
PS:Don't suggest installing extra libraries in Python,since I am not 100% sure our professor will be using said libraries to check our code.
weatherinfo
is a JSON-formatted string. In order to have a dictionary like access to it, you need to load it via json.load()
:
import json
weatherinfo = json.load(weatherbot)
print(weatherinfo["weather"][0]["main"]) # prints "Clear"
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.