Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit fca8e94

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 <[email protected]> Co-authored-by: Ezio Melotti <[email protected]> (cherry picked from commit 91f40f3) Co-authored-by: Erlend E. Aasland <[email protected]>
1 parent 5835911 commit fca8e94

File tree

1 file changed

+9
-18
lines changed

1 file changed

+9
-18
lines changed

Doc/library/sqlite3.rst

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -588,25 +588,16 @@ Connection objects
588588

589589
Example:
590590

591-
.. testcode::
592-
593-
def dict_factory(cursor, row):
594-
d = {}
595-
for idx, col in enumerate(cursor.description):
596-
d[col[0]] = row[idx]
597-
return d
598-
599-
con = sqlite3.connect(":memory:")
600-
con.row_factory = dict_factory
601-
cur = con.execute("SELECT 1 AS a")
602-
print(cur.fetchone()["a"])
603-
604-
con.close()
605-
606-
.. testoutput::
607-
:hide:
591+
.. doctest::
608592

609-
1
593+
>>> def dict_factory(cursor, row):
594+
... col_names = [col[0] for col in cursor.description]
595+
... return {key: value for key, value in zip(col_names, row)}
596+
>>> con = sqlite3.connect(":memory:")
597+
>>> con.row_factory = dict_factory
598+
>>> for row in con.execute("SELECT 1 AS a, 2 AS b"):
599+
... print(row)
600+
{'a': 1, 'b': 2}
610601

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

0 commit comments

Comments
 (0)