Python Sqlite3 returns the implementation of the query result in dictionary form

  • 2020-05-12 02:50:52
  • OfStack

sqlite3 itself does not have a native dictionary-like cursor like pymysql1.


cursor = conn.cursor(pymysql.cursors.DictCursor)

However, the official documentation has reserved the corresponding implementation plan.


def dict_factory(cursor, row): 
  d = {} 
  for idx, col in enumerate(cursor.description): 
    d[col[0]] = row[idx] 
  return d 

Use this function instead of the conn.raw_factory property.


con = sqlite3.connect(":memory:") # Open the database in memory 
con.row_factory = dict_factory
cur = con.cursor()
cur.execute("select 1 as a")
print cur.fetchone()["a"]

Official document link


Related articles: