Skip to content

Commit bbcb03e

Browse files
miss-islingtonErlend E. Aasland
and
Erlend E. Aasland
authored
gh-96168: Improve sqlite3 dict_factory example (GH-96457)
Co-authored-by: C.A.M. Gerlach <CAM.Gerlach@Gerlach.CAM> Co-authored-by: Ezio Melotti <ezio.melotti@gmail.com> (cherry picked from commit 91f40f3) Co-authored-by: Erlend E. Aasland <erlend.aasland@innova.no>
1 parent 2ecc195 commit bbcb03e

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
@@ -546,25 +546,16 @@ Connection objects
546546

547547
Example:
548548

549-
.. testcode::
550-
551-
def dict_factory(cursor, row):
552-
d = {}
553-
for idx, col in enumerate(cursor.description):
554-
d[col[0]] = row[idx]
555-
return d
556-
557-
con = sqlite3.connect(":memory:")
558-
con.row_factory = dict_factory
559-
cur = con.execute("SELECT 1 AS a")
560-
print(cur.fetchone()["a"])
561-
562-
con.close()
563-
564-
.. testoutput::
565-
:hide:
549+
.. doctest::
566550

567-
1
551+
>>> def dict_factory(cursor, row):
552+
... col_names = [col[0] for col in cursor.description]
553+
... return {key: value for key, value in zip(col_names, row)}
554+
>>> con = sqlite3.connect(":memory:")
555+
>>> con.row_factory = dict_factory
556+
>>> for row in con.execute("SELECT 1 AS a, 2 AS b"):
557+
... print(row)
558+
{'a': 1, 'b': 2}
568559

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

0 commit comments

Comments
 (0)