0

How do I create a table in sqlite3 with dictionary items as fields?

I can't simply define each and every field manually, since I have a lot of dictionaries of various sizes. Is there a way to accomplish this?

Here's what I've come up so far:

import sqlite3

DICT = {   'field 1': 'TEXT',
           'field 2': 'TEXT',
           'field 3': 'INT',
           'field 4': 'TEXT'
           'field x': '???'
            }

def create_table(DICT):

    with sqlite3.connect("data.db") as connection:
        cursor = connection.cursor()

        # should instead iterate over the dictionary and create a field for each entry
        cursor.execute("""CREATE TABLE table_name
                        (dict_key_x, DICT_VALUE_X)""")

        connection.close()

Any ideas are welcome. Thanks! :)

NightShadeQueen
  • 3,284
  • 3
  • 24
  • 37
St4rb0y
  • 317
  • 3
  • 5
  • 22

1 Answers1

2

You could certainly do exactly this by building a list of strings and using ',\n' .join

DICT = {'field 1': 'TEXT',
        'field 2': 'TEXT',
        'field 3': 'INT',
        'field 4': 'TEXT'
        'field x': '???'}

columns = "(" + ",\n".join(["{} {}".format(k,v) for k,v in DICT.items()]) + ")"
# looks like:
# # """(field 1 TEXT,
# # field 2 TEXT,
# # field 3 INT,
# # field 4 TEXT,
# # field x ???)"""

with sqlite.connect('data.db') as connection:
    cursor = connections.cursor()
    cursor.execute("CREATE TABLE table_name\n" + columns)
# you don't have to close the connection if you're using a with statement
Adam Smith
  • 52,157
  • 12
  • 73
  • 112
  • Thank you! It worked after I changed your columns formatting to 'columns = "("+", ".join("{} {}".format(k,v) for k,v in DICT.items())+")"'. This produces the following sqlite3 command: '"CREATE TABLE table_name (field 1 TEXT, field 2 TEXT, etc)"' Your suggestion returned an error, because the formatting was like this: '"CREATE TABLE table_name (field 1, TEXT), (field 2, TEXT), etc)"' – St4rb0y Jul 21 '15 at 08:44
  • @St4rb0y edited to reflect those changes. It's been beyond forever since I had to build raw SQL queries by hand -- I didn't remember the syntax! sqlalchemy is your friend :D – Adam Smith Jul 21 '15 at 15:24