• 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 191 views
0 votes
1 answer 14 views
Problem: How to I Solve this: typeerror: sequence item 0: expected str instance, int found HELP! I need help understanding this: typeerror: sequence item 0: expected str instance, int found Can someone please help solve this, I am new in python(). Someone have idea to solve this thanks!
asked Mar 5 Mashhoodch 13k points
1 vote
1 answer 78 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 147 views
0 votes
1 answer 124 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
0 votes
1 answer 54 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 13k points
1 vote
1 answer 734 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
0 answers 1 view
1 view
Problem: I'm a noob in programming and just started using python 3.x several days ago. Also I never proactively used this website before altough it already saved me multiple times when I was stuck.I really am not sure though, I hope that you can help me .
asked 1 day ago salim1 60.6k points
0 votes
1 answer 11 views
Problem: I'm only new, so don't be too harsh if this is really obvious, but why am i getting this error? >>> Enter muzzle velocity (m/2): 60 Enter angle (degrees): 45 Traceback (most recent call last): File "F:/Python31/Lib/idlelib/test", line 9, in <module> range() File " ... (2*(x*x))((decimal(math.zsin(y)))*(decimal(math.acos(y)))))/2) TypeError: can't multiply sequence by non-int of type 'str'
asked Apr 18 munim01 21k points