1

I need to take a list of information such as:

my_list = ['a','1','b','2','c','3','d','4']

I need to write this information as pairs into two separate columns in a .db file with sqlite3.

| a | 1 |
| b | 2 |
| c | 3 |
| d | 4 |

sqlite3 will not allow me to pass a list as an argument so I tired:

connection = sqlite3.connect('mytest.db')
cursor = conn.cursor
cursor.execute('CREATE TABLE IF NOT EXISTS test(c1 TEXT, c2 TEXT)')

for i in my_list[0:len(my_list):2]:
    cursor.execute(INSERT INTO test (c1) VALUES (?)',(i,))
    connection.commit

for i in my_list[1:len(my_list):2]:
    cursor.execute(INSERT INTO test (c2) VALUES (?)',(i,))
    connection.commit

However, this is making the table appear like so:

|  a   | null |
|  b   | null |
|  c   | null |
|  d   | null |
| null |  1   |
| null |  2   |
| null |  3   |
| null |  4   |
Chace Mcguyer
  • 415
  • 2
  • 7
  • 19

1 Answers1

1

You can do this with a pairwise iteration and executemany():

def pairwise(iterable):
    a = iter(iterable)
    return zip(a, a)

my_list = ['a','1','b','2','c','3','d','4']
cursor.executemany("""
    INSERT INTO 
        test (c1, c2) 
    VALUES 
        (?, ?)""", pairwise(my_list))
connection.commit()  # note: you need to call the commit method
Community
  • 1
  • 1
alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195