2013-10-18 78 views
0

這讓我瘋狂。我對Python和AppEngine都是新手,我似乎無法弄清楚這一點。我正在編寫一個由App Engine託管的簡單應用程序。我的問題是:我可以使用for循環訪問Python字典,但是我無法直接使用鍵字符串訪問字典中的項目。python字典鍵在應用程序引擎中無法訪問

我打電話返回以下JSON字符串JSON網絡服務:

{"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"} 

蟒蛇代碼是如下:

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

嘗試'爲簡稱,狀態的狀態:' – karthikr

+1

我可以得到它的工作,對沒有問題的循環。我的問題是我不能直接訪問字典使用它的關鍵像 '狀態[「IN」]''。我只是喜歡它會使用get方法。所以,如果我做'state.get(「IN」)'。它會工作。這太瘋狂了!!! – user2773013

+0

你確定「IN」包含在狀態中嗎? – Jesse

回答

3

您不能通過索引訪問字典,因爲它會認爲您嘗試使用具有該索引值的鍵訪問字典。

我相信.get()適合你,因爲即使密鑰不存在於字典中,.get()也會返回None,因此不會使應用程序崩潰。

確保在部署「IN」時確實在響應中。

到@karthikr類似的表示,它通常是更好的通過字典來遍歷方式:

for key, value in dictionary.iteritems() 
相關問題