How to Retrieve Dictionaries from SQLite Queries
When performing SQLite queries, you may encounter situations where you need to obtain data in dictionary format instead of lists. This article will provide you with several solutions to achieve this.
Using row_factory
The row_factory parameter in the SQLite connection allows you to specify how rows are returned. By setting it to a custom function, you can convert tuples to dictionaries:
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.cursor() cur.execute("select 1 as a") print(cur.fetchone()["a"]) # Output: 1
Using sqlite3.Row
Alternatively, you can set row_factory to sqlite3.Row, which provides an optimized way to access columns by both index and name:
con = sqlite3.connect(...) con.row_factory = sqlite3.Row # Set row_factory to sqlite3.Row cursor = con.cursor() row = cursor.fetchone() print(row["col1"]) # Access columns by name
Custom Implementation
If neither of the above solutions meets your needs, you can create your own custom implementation. However, this approach is generally not recommended due to potential performance issues in comparison to the provided solutions.
The above is the detailed content of How Can I Retrieve Dictionary Data from SQLite Queries?. For more information, please follow other related articles on the PHP Chinese website!