tag_id_query = select([tags.c.tagname, tags.c.id], tags.c.tagname.in_(hashtags)
    )
tag_ids = dict(conn.execute(tag_id_query).fetchall())
for tag in hashtags:
    if tag not in tag_ids:
        result = conn.execute(tags.insert(), {'tagname': tag})
tag_ids[tag] = result.last_inserted_ids()[0]
Setting up/Inserting into Many-to-Many Database with Python, SQLALchemy, Sqlite