2013-04-29 49 views
0

我有我的Python代碼來以下錯誤:列表索引必須是整數錯誤

if data['result'] == 0: 
TypeError: list indices must be integers, not str 

以下是代碼:

data = urllib.urlencode(parameters) 
req = urllib2.Request(url, data) 
try: 
    response = urllib2.urlopen(req) 
except urllib2.URLError, e: 
    self.redirect('/error') 
json_post = response.read() 
data = json.loads(json_post) 
response_dict = simplejson.loads(json_post) 

virustotal = VirusTotal() 
if data['result'] == 0: 
    virustotal_result = True 

elif data['result'] == -2: 
    self.response.out.write("API Request Rate Limit Exceeded<br/>") 
elif data['result'] == -1: 
    self.response.out.write("API Key provided is wrong<br/>") 
elif data['result'] == 1: 
    self.response.out.write("Time Stamp : %s<br/>"% data['report'][0]) 

我知道數據是一個列表。所以我將它改爲整數,但代碼顯示範圍錯誤。請幫忙??

+0

如果你打印'data',你會得到什麼? – thegrinner 2013-04-29 17:27:18

回答

1

當你說data = json.loads(json_post),這聽起來像你有一個清單,而不是你似乎期待的字典。

如果這不是問題,請嘗試使用完整回溯和值json_post進行更新。

+0

我是新來的python,我讀了關於字典和列表,但我不知道如何將它改爲整數索引。 – carol 2013-04-29 17:21:16

+2

答案取決於你對數據的理解。考慮閱讀http://docs.python.org/2/tutorial/以瞭解Python數據類型。 – 2013-04-29 17:24:20

1

您正在從response.read返回一組對象,這意味着您得到的是Python list。試試這個:

data = json.loads(json_post)[0] 
+0

它現在給出錯誤,「列表超出範圍」 – carol 2013-04-29 17:26:59

+0

然後,也許你沒有從讀取調用中得到任何東西。 – cwallenpoole 2013-04-29 17:27:57

相關問題