I’m pretty new to all of this, however though. In my code I’m trying to make Python grab Weather Information off of some free Weather API. However though, everything will go according to plan, it’ll get the Weather – Clear but when it comes to integers it freaks out, and most of the information needed are integers: Temp, Humidity, Wind Speed, etc.
This is where it fails:
for result in data['main']:
temp = result['temp']
print('Temperature: '+temp)
with open('data.txt', 'a') as f:
f.write(' '+temp)
f.write('\n')
The Table looks like:
'main': {'feels_like': 304.72,
'humidity': 67,
'pressure': 1011,
'temp': 301.84,
'temp_max': 303.85,
'temp_min': 299.19},
Main being the Dict.
I’ve tried adding [3] instead of ['temp'\]
for result in data['main']:
temp = result[3]
print('Temperature: '+temp)
with open('data.txt', 'a') as f:
f.write(' '+temp)
f.write('\n')
However though, the output was the first 3 letters of each category, like TEM – TEMP / HUM – HUMIDITY
I knew what it did but I just trusted some website. I don’t know any way to fix this and a lot of the websites just state, "Alter the JSON File" but I can’t really do that.
I’ve tried ‘Json.Loads’ but it states, must be ‘str, bytes, or bytearray, not dict.’
Traceback
File "location", line 30, in <module>
temp = result['temp']
TypeError: string indices must be integers
>Solution :
Your code:
for result in data['main']:
temp = result[3]
print('Temperature: '+temp)
with open('data.txt', 'a') as f:
f.write(' '+temp)
f.write('\n')
Iterates through the key values of data[‘main’]. In other words, every loop, result is a value in the list of ["feels_like", "humidity", "pressure", "temp", "temp_max", "temp_min"]
What you actually want to do:
for result in data["main"]:
if result == "temp":
print("Temperature: %0.2f" % data["main"][result])
with open("data.txt", "a") as f:
f.write(" %0.2f\n" % data["main"][result])
or even:
for field, result in data["main"].items():
if field == "temp":
print("Temperature: %0.2f" % result)
with open("data.txt", "a") as f:
f.write(" %0.2f\n" % result)
which grabs both the key and value from the dictionary data["main"].