I want to create a table in my MySQL database, from a dictionary which will dynamically change over time.
The dictionary looks as followed, which specify's the name
+ type
of the columns to be created. Which is a settings file which the user fills in before the project is run.
dct = {'ID':'String',
'Benefit':'Float',
'Premium':'Float'}
I know how to create this by hardcoding this in a mapping class as followed:
from sqlalchemy import create_engine, Column, String, Float
from sqlalchemy.ext.declarative import declarative_base
engine = create_engine('mysql+mysqldb://...')
Base = declarative_base()
class Table(base):
__tablename__ = 'example'
id = Column(String(30), primary_key=True)
benefit = Column(Float)
Premium = Column(Float)
Question: How would I create these tables without hardcoding the names and types, but substracting these from the dictionary.
I also tried to construct a class from dict:
class Policy:
def __init__(self, dictionary):
for k, v in dictionary.items():
setattr(self, k, v)
But didn't knew how to implement this further.
Similar questions: