0

这真让我抓狂。我对 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。

4

1 回答 1

3

您不能按索引访问字典,因为它会认为您正在尝试使用具有该索引值的键来访问字典。

我相信.get()对您有用,因为即使字典中不存在密钥,.get()也会返回None,因此不会使您的应用程序崩溃。

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

与@karthikr 说的类似,通常最好通过以下方式遍历字典:

for key, value in dictionary.iteritems()
于 2013-10-18T22:51:50.603 回答