Skip to content

Commit 91f40f3

Browse files
Erlend E. AaslandCAM-Gerlachezio-melotti
authored
gh-96168: Improve sqlite3 dict_factory example (#96457)
Co-authored-by: C.A.M. Gerlach <CAM.Gerlach@Gerlach.CAM> Co-authored-by: Ezio Melotti <ezio.melotti@gmail.com>
1 parent 4c72517 commit 91f40f3

File tree

1 file changed

+9
-18
lines changed

1 file changed

+9
-18
lines changed

Doc/library/sqlite3.rst

+9-18
Original file line numberDiff line numberDiff line change
@@ -601,25 +601,16 @@ Connection objects
601601

602602
Example:
603603

604-
.. testcode::
605-
606-
def dict_factory(cursor, row):
607-
d = {}
608-
for idx, col in enumerate(cursor.description):
609-
d[col[0]] = row[idx]
610-
return d
611-
612-
con = sqlite3.connect(":memory:")
613-
con.row_factory = dict_factory
614-
cur = con.execute("SELECT 1 AS a")
615-
print(cur.fetchone()["a"])
616-
617-
con.close()
618-
619-
.. testoutput::
620-
:hide:
604+
.. doctest::
621605

622-
1
606+
>>> def dict_factory(cursor, row):
607+
... col_names = [col[0] for col in cursor.description]
608+
... return {key: value for key, value in zip(col_names, row)}
609+
>>> con = sqlite3.connect(":memory:")
610+
>>> con.row_factory = dict_factory
611+
>>> for row in con.execute("SELECT 1 AS a, 2 AS b"):
612+
... print(row)
613+
{'a': 1, 'b': 2}
623614

624615
If returning a tuple doesn't suffice and you want name-based access to
625616
columns, you should consider setting :attr:`row_factory` to the

0 commit comments

Comments
 (0)