Python dictionary is not accessible in Google App Engine using square brackets

My code is pulling JSON data from a web service I wrote. That JSON data is then loaded into a python dictionary. Things works fabulously when I debug in my local console running an internal web server provided by the App Engine SDK. But when I upload the application to Goole CLoud Engine, things break. This is a snippet of my code

states=dict()
population_data=""
url="http://something.com/json"
try:
   response=urllib2.urlopen(url)
   states=json.load(response,"utf-8")
except Exception as ex:
   self.response.write("Google says: %s"%(ex.message))
   self.response.write("Try refreshing the page (again)")
   SystemExit(0)

I have all the states abbreviation as keys. when I try to access the value of the dictionary directly using square brackets, like

states["IN"]

Google App Engine complains about KeyError exception. However if I try iterating through the key using a for loop, like

for each_state in states:
   self.response.write(states[each_state])

it works flawlessly in the App Engine. I also found out that the following also works perfectly

self.response.write(states.get("IN"))

The only thing I cannot do is accessing the dictionary using square brackets. That baffles me. If you know what’s up with that, drop me a line.

Leave a Reply

Your email address will not be published. Required fields are marked *

*