How to add all elements from python dictionary to database?
Question: I'm trying to add the elements of a dictionary to the database. I'm completely
new to working with databases and I'm just wondering if I'm doing it right or
not, because it seems to me that not. If so, how can I do it ? And how can I
print all the elements of the database then ?

    
    
    from sqlalchemy import Column, String, Integer, create_engine
    from sqlalchemy.orm import relationship, sessionmaker
    from sqlalchemy.ext.declarative import declarative_base
    
    Base = declarative_base()
    
    class Person(Base):
        __tablename__ = 'person'
        id = Column(Integer, primary_key = True)
        name = Column(String(250), nullable=False)
        job = Column(String(250), nullable=False)
    
    engine = create_engine('sqlite:///persons.sqlite')
    session = sessionmaker()
    session.configure(bind=engine)
    Base.metadata.create_all(engine)
    
    dct = {'John':'doctor', 'Alice':'typist'}
    
    for el in dct:
        np = Person(name=el, job=dct[el])
        s = session()
        s.add(np)
        s.commit() 
    


Answer: You don't need to create a new session for each item:

    
    
    s = session()
    for name, job in dct.iteritems():
        np = Person(name=name, job=job)
        s.add(np)
        s.commit() 
    

