how create table in sqlite3 dictionary items fields?
i can't define each , every field manually, since have lot of dictionaries of various sizes. there way accomplish this?
here's i've come far:
import sqlite3 dict = { 'field 1': 'text', 'field 2': 'text', 'field 3': 'int', 'field 4': 'text' 'field x': '???' } def create_table(dict): sqlite3.connect("data.db") connection: cursor = connection.cursor() # should instead iterate on dictionary , create field each entry cursor.execute("""create table table_name (dict_key_x, dict_value_x)""") connection.close() any ideas welcome. thanks! :)
you building list of strings , using ',\n' .join
dict = {'field 1': 'text', 'field 2': 'text', 'field 3': 'int', 'field 4': 'text' 'field x': '???'} columns = "(" + ",\n".join(["{} {}".format(k,v) k,v in dict.items()]) + ")" # looks like: # # """(field 1 text, # # field 2 text, # # field 3 int, # # field 4 text, # # field x ???)""" sqlite.connect('data.db') connection: cursor = connections.cursor() cursor.execute("create table table_name\n" + columns) # don't have close connection if you're using statement
Comments
Post a Comment