St4rb0y
St4rb0y

Reputation: 309

New Table with Fields from Dictionary?

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! :)

Upvotes: 0

Views: 1114

Answers (1)

Adam Smith
Adam Smith

Reputation: 54163

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

Upvotes: 2

Related Questions