ocean O
asked on
Python
I am new to python and have a question about python.
I have some python code : after get results from db, then need write each row to a csv file. but I got an error when I try to access each row, I got an error: "tuple indices must be integers or slices, not str"
sample data for each row is like this:
150, Decimal('80'), Decimal('-25'), 'NJ', '00700')
Below is the code:
with open ('my.csv','w') as awriter:
fieldnames = ['id', 'la', 'lo', 'state', 'zip']
csvwriter = csv.DictWriter(awriter, fieldnames=fieldnames)
csvwriter.writeheader()
for row in results:
id = row['id'] //error start here, can't retrieve the value for fields
la = row['la']
lo = row['lo']
state = row['state']
zip1 = row['zip']
line = ''.join([id, ",", la, ",", lo, ",", state, ",", zip1]).split(",")
ln_dict = OrderedDict(zip(fieldnames , line))
csvwriter.writerow(ln_dict )
Any inputs are appreciated!
I have some python code : after get results from db, then need write each row to a csv file. but I got an error when I try to access each row, I got an error: "tuple indices must be integers or slices, not str"
sample data for each row is like this:
150, Decimal('80'), Decimal('-25'), 'NJ', '00700')
Below is the code:
with open ('my.csv','w') as awriter:
fieldnames = ['id', 'la', 'lo', 'state', 'zip']
csvwriter = csv.DictWriter(awriter, fieldnames=fieldnames)
csvwriter.writeheader()
for row in results:
id = row['id'] //error start here, can't retrieve the value for fields
la = row['la']
lo = row['lo']
state = row['state']
zip1 = row['zip']
line = ''.join([id, ",", la, ",", lo, ",", state, ",", zip1]).split(",")
ln_dict = OrderedDict(zip(fieldnames
csvwriter.writerow(ln_dict
Any inputs are appreciated!
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Hi,
As strings are awaited by join method all numeric variable should be pass using an str() function.
So :
for row in results:
id = str(row[0])
la = str(row[1])
lo = str(row[2])
state = row[3] # already string type
zip1 = row[4] # already string type
As strings are awaited by join method all numeric variable should be pass using an str() function.
So :
for row in results:
id = str(row[0])
la = str(row[1])
lo = str(row[2])
state = row[3] # already string type
zip1 = row[4] # already string type
ASKER
but I got an error on this line:
line = ''.join([id, ",", la, ",", lo, ",", state, ",", zip1]).split(",") //error happening here: sequence item 0:expected str indtance, int found
ln_dict = OrderedDict(zip(fieldnames
csvwriter.writerow(ln_dict