Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
Split dict row factory example in two
  • Loading branch information
erlend-aasland committed Nov 25, 2022
commit f9fa2ee1fbf9879f9e4c1f94cc071f7c665af2e8
16 changes: 10 additions & 6 deletions Doc/library/sqlite3.rst
Original file line number Diff line number Diff line change
Expand Up @@ -2386,14 +2386,18 @@ Queries now return :class:`!Row` objects:
>>> row["RADIUS"] # Column names are case-insensitive.
6378

To create and use a custom :attr:`~Cursor.row_factory`,
in this case returning a :class:`dict` mapping column names to values:
You can create a custom :attr:`~Cursor.row_factory`
that returns each row as a :class:`dict`, mapping column names to values:

.. doctest::
.. testcode::

def dict_factory(cursor, row):
fields = [column[0] for column in cursor.description]
return {key: value for key, value in zip(fields, row)}

Using it, queries now return a :class:`!dict` instead of a :class:`!tuple`:

>>> def dict_factory(cursor, row):
... col_names = [column[0] for column in cursor.description]
... return {key: value for key, value in zip(col_names, row)}
.. doctest::

>>> con = sqlite3.connect(":memory:")
>>> con.row_factory = dict_factory
Expand Down