0

I'm trying to get the hourly forecast from the Wunderground API but my code returns this error.

Traceback (most recent call last): File "weathergraph.py", line 10, in forecast = parsed_json['hourly_forecast']['FCTTIME']['temp']['english'] TypeError: list indices must be integers, not str

This is my code.

f=urllib2.urlopen('http://api.wunderground.com/api/mykey/hourly/q/NY/New_York_City.json')

json_string = f.read()

parsed_json = json.loads(json_string)

forecast = parsed_json['hourly_forecast']['FCTTIME']['temp']['english']

f.close()

parsed_json = http://pastie.org/3905346

A Clockwork Orange
  • 23,913
  • 7
  • 25
  • 28
  • At some point on the `forecast = ` line you are accessing a list, not a dictionary. You should break that line up into four lines and determine exactly which instance is causing the exception. – brady May 13 '12 at 13:48
  • Okay, now how do I access a json list in Python? And how do I tell the difference in the JSON itself? – A Clockwork Orange May 13 '12 at 13:59
  • After some testing, this works: forecast = parsed_json['hourly_forecast']. But this does not: forecast = parsed_json['hourly_forecast']['FCTTIME']. So FCCTTIME and everything that follows is the weird one? How do I handle that then? – A Clockwork Orange May 13 '12 at 14:05
  • Add the line print parsed_json right after you assign parsed_json. Post that output in your question and we will be able to tell you how to extract the information. – ditkin May 13 '12 at 14:20
  • Done. Putting it in a pastie. – A Clockwork Orange May 13 '12 at 14:51

1 Answers1

3

1) The value of hourly_forecast is a list of dicts, not a dict. Looks like about 36 in the list.

2) temp is not an element of FCTTIME. They are at the same level

This should not generate an error:

forecast = parsed_json['hourly_forecast'][-1]['temp']['english'] 

It looks like the list is in order by time, so the last one is most recent. Checking the contents of FCTTIME will tell you whether it is different from the last time that you read it.

stark
  • 12,615
  • 3
  • 33
  • 50