在app引擎中无法访问python词典键

时间:2013-10-18 19:03:06

标签: python json google-app-engine dictionary

这让我发疯了。我是python和AppEngine的新手,我似乎无法解决这个问题。我正在编写一个由App Engine托管的简单应用程序。我的问题是:我可以使用for循环访问python字典,但我无法使用密钥字符串直接访问字典中的项目。

我正在调用一个返回以下JSON字符串的JSON Web服务:

{"WA": "Washington", "DE": "Delaware", "DC": "District of Columbia", "WI": "Wisconsin", "WV": "West Virginia", "HI": "Hawaii", "FL": "Florida", "WY": "Wyoming", "NH": "New Hampshire", "NJ": "New Jersey", "NM": "New Mexico", "TX": "Texas", "LA": "Louisiana", "NC": "North Carolina", "ND": "North Dakota", "NE": "Nebraska", "TN": "Tennessee", "NY": "New York", "PA": "Pennsylvania", "CA": "California", "NV": "Nevada", "VA": "Virginia", "CO": "Colorado", "AK": "Alaska", "AL": "Alabama", "AR": "Arkansas", "VT": "Vermont", "IL": "Illinois", "GA": "Georgia", "IN": "Indiana", "IA": "Iowa", "MA": "Massachusetts", "AZ": "Arizona", "ID": "Idaho", "CT": "Connecticut", "ME": "Maine", "MD": "Maryland", "OK": "Oklahoma", "OH": "Ohio", "UT": "Utah", "MO": "Missouri", "MN": "Minnesota", "MI": "Michigan", "RI": "Rhode Island", "KS": "Kansas", "MT": "Montana", "MS": "Mississippi", "SC": "South Carolina", "KY": "Kentucky", "OR": "Oregon", "SD": "South Dakota"}

python代码如下:

states=dict()

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

这是令人困惑的地方。以下语句执行得很好:

for each in states:
  self.response.write(states[each])
  self.response.write("<br>")
  self.response.write(each)
  self.response.write("<br>")

但是我需要使用它的密钥来引用字典。所以,我这样做了:

self.response.write(states["IN"])

这不起作用。谷歌说:

File "/base/data/home/apps/bu3245/1.371010709629673028/test.py", line 42, in get
self.response.write(states["IN"])
KeyError: 'IN'

我做错了什么? 当我在本地调试时,代码可以工作,但是当它在应用程序引擎上时它不起作用。我可以通过for循环看到所有键和值吐出,但如果我使用其键访问字典,它将告诉我关键错误。如果我尝试使用整数作为索引,它也会说KeyError。

1 个答案:

答案 0 :(得分:3)

您无法通过索引访问字典,因为它会认为您尝试使用值为该索引的键访问字典。

我相信.get()适合您,因为即使字典中不存在该密钥,.get()也会返回None,因此不会导致您的应用崩溃。

确保在部署时“IN”确实在响应中。

与@karthikr相似,通常通过以下方式迭代字典更好:

for key, value in dictionary.iteritems()