sqlite3 row_factory Returns Dict Rows
Return SQLite rows as mappings with row_factory, read columns by name, and switch to plain dict rows with a custom factory.
Code
import sqlite3
def main() -> None:
conn = sqlite3.connect(':memory:')
conn.row_factory = sqlite3.Row # 支持按列名取值
conn.execute('CREATE TABLE jobs (id INTEGER PRIMARY KEY, name TEXT, priority INTEGER)')
conn.executemany(
'INSERT INTO jobs (name, priority) VALUES (?, ?)',
[('build', 2), ('lint', 1), ('deploy', 3)],
)
rows = conn.execute('SELECT id, name, priority FROM jobs ORDER BY priority DESC').fetchall()
for row in rows:
print(row['id'], row['name'], row['priority'])
print('keys:', list(rows[0].keys()))
# 自定义 row_factory:返回普通 dict
def as_dict(cursor, row):
return {col[0]: value for col, value in zip(cursor.description, row)}
conn.row_factory = as_dict
mapped = conn.execute('SELECT name FROM jobs WHERE priority > ?', (1,)).fetchall()
print('dict rows:', mapped)
conn.close()
if __name__ == '__main__':
main()How the snippet works
Count the functions main and as_dict as the entire surface area of sqlite3 row_factory Returns Dict Rows.
Repetition is confined to for row in rows — the rest of the file is straight-line.
Returns a newly built value, leaving the inputs as they were.
What to watch for
- Requires
sqlite3as a package; the snippet will not run without it.
Applying it
Output lines are prefixed (keys:, dict rows:), making each step’s effect easy to spot.
Treat main as the orchestrator calling as_dict in a fixed order.
Statements that matter
return {col[0]: value for col, value in zip(cursor.description, row)}
FAQ
- Does `main` modify its input?
- No — a new value is constructed for the result and the arguments are never written to.
- What does this need from the package registry?
- These are real dependencies: `sqlite3`. Without it the snippet will not load.
Report a problem with this exampleOpens a pre-filled issue on GitHub.