diff options
author | Erlend E. Aasland <erlend.aasland@innova.no> | 2022-09-01 21:47:59 (GMT) |
---|---|---|
committer | GitHub <noreply@github.com> | 2022-09-01 21:47:59 (GMT) |
commit | 91f40f3f78d6016a283989e32ec3d1fb61bcebca (patch) | |
tree | 09bcf9a52b7c9ed2452673311c76b17918dfb120 /Doc | |
parent | 4c72517cada147b215cf30ff8dac70ea0f08f1e0 (diff) | |
download | cpython-91f40f3f78d6016a283989e32ec3d1fb61bcebca.zip cpython-91f40f3f78d6016a283989e32ec3d1fb61bcebca.tar.gz cpython-91f40f3f78d6016a283989e32ec3d1fb61bcebca.tar.bz2 |
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>
Diffstat (limited to 'Doc')
-rw-r--r-- | Doc/library/sqlite3.rst | 27 |
1 files changed, 9 insertions, 18 deletions
diff --git a/Doc/library/sqlite3.rst b/Doc/library/sqlite3.rst index 7ac7162..b188ca4 100644 --- a/Doc/library/sqlite3.rst +++ b/Doc/library/sqlite3.rst @@ -601,25 +601,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 |