user7070824 user7070824 - 1 month ago 14
Python Question

getting error about string indices must be integers

I am getting the error message : Traceback (most recent call last):
File "", line 10, in
TypeError: string indices must be integers . please help me.

the python 2.7 script sample:

import csv
cursor = db.job_templates.find( {}, {'_id': 1, 'rangePercents.questionnaire': 1, 'rangePercents.termMap': 1})
with open('range_percent1.csv', 'wt') as outfile:
fields = ['_id', 'questionnaire', 'termMap']
write = csv.DictWriter(outfile, fieldnames=fields)
write.writeheader()
for x in cursor:
x_id = x['_id']
for y in x['rangePercents']:
z = {
'_id': x_id,
'rangePercents.questionnaire': y['questionnaire'],
'rangePercents.termMap': y['termMap']}
write.writerow(z)


the data sample is

"_id": ObjectID("51dc52fec0d988a9547b5201"),
"rangePercents": {
"termMap": 0,
"questionnaire": 100
}

Answer

Don't iterate over x['rangePercents'], you already can access everything in it through x. If you iterate like you're doing, you just get each key of your dictionary as y, which is a string and thus why you get your error. Try this:

for x in cursor:
    x_id = x['_id']
    y = x['rangePercents']
    z = {
         '_id': x_id,
         'rangePercents.questionnaire': y['questionnaire'],
         'rangePercents.termMap': y['termMap']}                               
    write.writerow(z)
Comments