简体   繁体   中英

TypeError: string indices must be integers - Python

I've found an "TypError" and I don't know how to solve it anymore. Please, some help. I'll really appreciate an explanation if is possible.

My code:

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

Error:

; 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]

info is a dict but you're iterating it like a list. I think you want to iterate on info['subjects'] .

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

Your for loop is not working how you think it does.

for item in info loops over the keys of your dictionary, ie over 'text' and 'subjects'. Then you try do index into these strings with another string, which is bound to fail.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM