2015-12-19 44 views
0

我發現了一個「TypError」,我不知道如何解決它。請幫忙。如果可能,我會非常感激的解釋。TypeError:字符串索引必須是整數 - Python

我的代碼:

import json 

input = '''{ 
    "text":"Sample data", 
    "subjects":[ 
    { 
     "id":"A", 
     "quant":10 
    }, 
    { 
     "id":"B", 
     "quant":9 
    }, 
    { 
     "id":"C", 
     "quant":8 
    }, 
    { 
     "id":"D", 
     "quant":7 
    }, 
    { 
     "id":"E", 
     "quant":6 
    }]} 
''' 

info = json.loads(input) 

count = 0 
total = 0 
for item in info: 
    value = item["subjects"][0]["quant"] 
    value = int(value) 
    total += value 
    count += count 

print 'Count: ', count  
print 'Sum: ', total 

錯誤:

; exit; {u'text': u'Sample data', u'subjects': [{u'quant': 10, u'id': u'A'}, {u'quant': 9, u'id': u'B'}, {u'quant': 8, u'id': u'C'}, {u'quant': 7, u'id': u'D'}, {u'quant': 6, u'id': u'E'}]} Traceback (most recent call last): File "/Users/macme/Documents/Python/test_Json.py", line 61, in value = item["subjects"][0]["quant"] TypeError: string indices must be integers logout Saving session... ...copying shared history... ...saving history...truncating history files... ...completed.

[Process completed]

+0

抱歉關於錯誤框格式。 – RBB

回答

4

info是一個字典,但你迭代它像一個列表。我想你想在info['subjects']上迭代。

for item in info['subjects']: 
    value = int(item['quant']) 
+0

謝謝丹。你真的幫助我,因爲現在我明白了爲什麼我得到這個錯誤。非常感謝! – RBB

1

您的for循環無法正常工作,您是如何看待它的。

for item in info循環遍歷字典的關鍵字,即通過「文本」和「主題」。然後你嘗試用另一個字符串來索引這些字符串,這將會失敗。

相關問題