LoginSignup
7
7

More than 5 years have passed since last update.

[Python] SQLite3で検索結果をdict形式で取得する

Posted at

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

7
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
7
7