我正在调用一个返回以下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。
答案 0 :(得分:3)
您无法通过索引访问字典,因为它会认为您尝试使用值为该索引的键访问字典。
我相信.get()
适合您,因为即使字典中不存在该密钥,.get()
也会返回None
,因此不会导致您的应用崩溃。
确保在部署时“IN”确实在响应中。
与@karthikr相似,通常通过以下方式迭代字典更好:
for key, value in dictionary.iteritems()