summaryrefslogtreecommitdiffstats
path: root/Doc/library/sqlite3.rst
diff options
context:
space:
mode:
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>2022-09-01 21:55:41 (GMT)
committerGitHub <noreply@github.com>2022-09-01 21:55:41 (GMT)
commitbbcb03e7b07ecf6f3ed0c308f72bc10f928c85a8 (patch)
tree36e16a6139f689fb2063d763ddcc81183e62f5c6 /Doc/library/sqlite3.rst
parent2ecc195498f3b1256fabc2b66e0d8f6d671fa1d7 (diff)
downloadcpython-bbcb03e7b07ecf6f3ed0c308f72bc10f928c85a8.zip
cpython-bbcb03e7b07ecf6f3ed0c308f72bc10f928c85a8.tar.gz
cpython-bbcb03e7b07ecf6f3ed0c308f72bc10f928c85a8.tar.bz2
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 91f40f3f78d6016a283989e32ec3d1fb61bcebca) Co-authored-by: Erlend E. Aasland <erlend.aasland@innova.no>
Diffstat (limited to 'Doc/library/sqlite3.rst')
-rw-r--r--Doc/library/sqlite3.rst27
1 files changed, 9 insertions, 18 deletions
diff --git a/Doc/library/sqlite3.rst b/Doc/library/sqlite3.rst
index b24fa48..5a467d3 100644
--- a/Doc/library/sqlite3.rst
+++ b/Doc/library/sqlite3.rst
@@ -546,25 +546,16 @@ Connection objects
Example:
- .. testcode::
-
- def dict_factory(cursor, row):
- d = {}
- for idx, col in enumerate(cursor.description):
- d[col[0]] = row[idx]
- return d
-
- con = sqlite3.connect(":memory:")
- con.row_factory = dict_factory
- cur = con.execute("SELECT 1 AS a")
- print(cur.fetchone()["a"])
-
- con.close()
-
- .. testoutput::
- :hide:
+ .. doctest::
- 1
+ >>> def dict_factory(cursor, row):
+ ... col_names = [col[0] for col in cursor.description]
+ ... return {key: value for key, value in zip(col_names, row)}
+ >>> con = sqlite3.connect(":memory:")
+ >>> con.row_factory = dict_factory
+ >>> for row in con.execute("SELECT 1 AS a, 2 AS b"):
+ ... print(row)
+ {'a': 1, 'b': 2}
If returning a tuple doesn't suffice and you want name-based access to
columns, you should consider setting :attr:`row_factory` to the