[Python] SQLite3で検索結果をdict形式で取得する
5147 ワード
Python: SQLite3で検索結果をdict形式で取得する
PythonでPostgreSQLを使用する際、psycopg2でDictCursorを使用すると検索結果をdictで扱えるため便利ですが、簡単に作りたいときや案件によってはSQLite3という選択肢することが出てくると思います。
SQLite3標準では検索結果がタプルで復帰するため、コーディングにおいて戸惑うだけでなく、メンテナンス性も落ちてしまいます。
対処方法を調べたところ、row_factoryを定義することで簡単に実現できることがわかりました。
SQLLite3の標準ファクトリを使用する
std_factory.py
import sqlite3
conn = sqlite3.connect(':memory:')
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.execute("select 'Abe' key, 1 as value")
row = cur.fetchone()
print("key: ", row['key'])
print("value: ", row['value'])
cur.close()
独自ファクトリを使用する
org_factory.py
import sqlite3
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
conn = sqlite3.connect(':memory:')
conn.row_factory = dict_factory
cur = conn.cursor()
cur.execute("select 'Abe' key, 1 as value")
row = cur.fetchone()
print("key: ", row['key'])
print("value: ", row['value'])
cur.close()
実行結果
key: Abe
value: 1
これでSQLite3でも可読性があがりますね!
(参考)
https://docs.python.jp/3.6/library/sqlite3.html#sqlite3.Connection.row_factory
Author And Source
この問題について([Python] SQLite3で検索結果をdict形式で取得する), 我々は、より多くの情報をここで見つけました https://qiita.com/nekobake/items/aebd40e07037fc7911bc著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .