• Register
1 vote


I was trying to insert data from one of my dictionaries into my database for that I wrote the code:

def all_db_inserts(dbinformation):
        rows = dbinfo['datarows']

        for row in rows:
            field_names = ",".join(["'{0}'".format(x) for x in row.keys()])
            value_list = row.values()

            for pos, value in enumerate(value_list):
                if isinstance(value, str):
                    value_list[pos] = "'{0}'".format(value)
                elif isinstance(value, datetime):
                    value_list[pos] = "'{0}'".format(value.strftime('%Y-%m-%d'))

            values = ",".join(value_list)

            sql = "INSERT INTO table_foobar ({0}) VALUES ({1})".format(field_names, values)

    except Exception as x:
        print 'BARFED with msg:',x

But I got this error message when I try to run this(using sample data):

TypeError: sequence item 0: expected string, int found

Can anyone help me out?

10 7 2
6,060 points

Please log in or register to answer this question.

2 Answers

0 votes
Best answer


You are having this error because of the line:
values = ",".join(value_list)

What to do:

You should replace

values = ",".join(value_list)


values = ','.join([str(i) for i in value_list])


values = ','.join(str(value_list)[1:-1])


values = ','.join(map(str, value_list))

If it is still not working for you let me know about it and fell free to ask me anything.

Happy coding.

11 6 4
34,950 points
0 votes

Be aware that some values could be Unicode strings and may cause the str to throw a UnicodeEncodeError error.

Solution 1:

In that cause replace the str function by the function Unicode.


Assume the string libie(Dutch for Libya) represented as the Unicode string u’Libi\xeb’ in python.

print str(u ‘Libi\xeb’)

This will throw an error;

Traceback (most recent call last):

  File "/Users/tomasz/Python/MA-CIW-Scriptie/RecreateTweets.py", line 21, in <module>

    print str(u'Libi\xeb')

UnicodeEncodeError: 'ascii' codec can't encode character u'\xeb' in position 4: ordinal not in range(128)

The following line will throw an error message;

print unicode(u'Libi\xeb') # prints Libië

so replace the line;

values = ','.join([str(i) for i in value_list])

with the following line of code;

values = ','.join([unicode(i) for i in value_list])

This will help to avoid errors.

Solution 2:

Replace the following lines of code;

values = ",".join(value_list)

with the one of the following line;

values = ','.join([str(i) for i in value_list])


values = ','.join(str(value_list)[1:-1])

Solution 3:

The user can also convert the integer data frame into a string first and then do the operations. This can be done by using the following line of code;


grp = df3.groupby('userID')['nID'].aggregate(lambda x: '->'.join(tuple(x)))


11 5 2
3,890 points

Related questions

0 votes
1 answer 103 views
0 votes
1 answer 103 views
1 vote
1 answer 67 views
Problem: I am working on python string. import string import re str = "Hello" b = 0 srr = "" for a in str: srr[b] = a #'str' object does not support item assignment b = b + 1 print (srr) This is my sample code. I was trying to read some characters from a string and put it into another string like C or Java but it&rsquo;s not working for my case. Thanks. I must recognize your help.
asked Mar 7, 2020 Gavin 15.3k points
0 votes
1 answer 14 views
Problem: On the last line, I got this error: builtins.TypeError: must be str, not bytes File "C:\PythonExamples\XmlReportGeneratorExample.py", line 29, in <module> doc.write(outFile) File "c:\Python32\Lib\site-packages\lxml\etree.pyd", line 1853, in lxml.etree._ElementTree.write (src/ ... etree.c:89527) I've installed Python 3.2, and I've installed lxml-2.3.win32-py3.2.exe. On Python 2.7 it works.
asked Jan 9 Mashhoodch 10.2k points
0 votes
1 answer 79 views
I was looking for a way to run an external process from python script and print its stdout messages during the execution. The code below works, but prints no stdout output during runtime. When it exits I am getting the following error: sys.stdout.write(nextline) TypeError:must ... .stdout.write(nextline) sys.stdout.flush() output = p.communicate()[0] exitCode = p.returncode I am using python 3.3.2
asked Oct 24, 2020 psandprop 2.4k points
1 vote
1 answer 601 views
Problem: I am getting the following error : error: array initializer must be an initializer list or string literal For the array; char x[80] = GetString(); Can any body explain or help?
asked Apr 2, 2020 LizzyM 6.1k points
0 votes
1 answer 26 views
Problem: Hi! I am new to the world of programming. I am trying to multiply two numbers that will be entered by the user. I wrote the following program: number1 = input("Enter first number: ") number2 = input("Enter second number: ") print(number1," * ",number2," = ", ... = ",number1*number2) TypeError: can't multiply sequence by non-int of type 'str' I have no idea what I am doing wrong. Any help?
asked Dec 21, 2020 Code Learner 6.3k points
1 vote
1 answer 749 views
Problem : I am learning to use Python. Currently I want to iterate through the files which are present in the folder on the local machine and then want to upload only those files whose file names have "Service_Areas" to the required FTP site with the use of ... rb')) TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader Please guide me in fixing my python ftp related error.
asked May 14, 2020 Martin K 6.6k points
0 votes
1 answer 5.6K views
Problem : I am very new to python. I am doing file handling for the first time. I am trying to iterate through the group of files in my folder on my local machine and upload only ones where a file names contain "Service_Areas" to the FTP site using my below ... open(file, 'rb')) TypeError: expected str, bytes or os.PathLike object, not _io.BufferedReader Any suggestions how can I fix the error?
asked Jan 28, 2020 jwilliam 3.9k points