152
db = sqlite.connect("test.sqlite")
res = db.execute("select * from table")

反復により、行に対応するリストを取得します。

for row in res:
    print row

列の名前を取得できます

col_name_list = [tuple[0] for tuple in res.description]

しかし、リストの代わりに辞書を取得する機能または設定はありますか?

{'col1': 'value', 'col2': 'value'}

または私は自分でしなければなりませんか?

4

15 に答える 15

219

ドキュメントの例のように、row_factoryを使用できます。

import sqlite3

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"]

または、ドキュメントのこの例の直後に示されているアドバイスに従います。

タプルを返すだけでは不十分で、列への名前ベースのアクセスが必要な場合は、row_factory を高度に最適化された sqlite3.Row タイプに設定することを検討する必要があります。Row は、メモリーのオーバーヘッドがほとんどない列へのインデックスベースおよび大文字と小文字を区別しない名前ベースのアクセスの両方を提供します。おそらく、独自のカスタム辞書ベースのアプローチや db_row ベースのソリューションよりも優れているでしょう。

この 2 番目のソリューションのコードは次のとおりです。

con.row_factory = sqlite3.Row
于 2010-07-21T14:47:20.827 に答える
23

sqlite3.Row クラスを使用しても、次の形式で文字列フォーマットを使用することはできません。

print "%(id)i - %(name)s: %(value)s" % row

これを乗り越えるために、行を取得して辞書に変換するヘルパー関数を使用します。これは、ディクショナリ オブジェクトが Row オブジェクトよりも望ましい場合にのみ使用します (たとえば、Row オブジェクトがディクショナリ API をネイティブにサポートしていない文字列の書式設定などの場合)。ただし、それ以外の場合は常に Row オブジェクトを使用してください。

def dict_from_row(row):
    return dict(zip(row.keys(), row))       
于 2012-03-02T18:19:59.670 に答える
18

SQLite に接続したら、次を con = sqlite3.connect(.....)実行するだけで十分です。

con.row_factory = sqlite3.Row

出来上がり!

于 2019-05-04T21:31:34.650 に答える
8

PEP 249から:

Question: 

   How can I construct a dictionary out of the tuples returned by
   .fetch*():

Answer:

   There are several existing tools available which provide
   helpers for this task. Most of them use the approach of using
   the column names defined in the cursor attribute .description
   as basis for the keys in the row dictionary.

   Note that the reason for not extending the DB API specification
   to also support dictionary return values for the .fetch*()
   methods is that this approach has several drawbacks:

   * Some databases don't support case-sensitive column names or
     auto-convert them to all lowercase or all uppercase
     characters.

   * Columns in the result set which are generated by the query
     (e.g.  using SQL functions) don't map to table column names
     and databases usually generate names for these columns in a
     very database specific way.

   As a result, accessing the columns through dictionary keys
   varies between databases and makes writing portable code
   impossible.

そうです、自分でやってください。

于 2010-07-21T14:46:42.613 に答える
1

あなたは正しい軌道に乗っていたと思います。これを非常に単純にして、あなたがやろうとしていたことを完成させましょう:

import sqlite3
db = sqlite3.connect("test.sqlite3")
cur = db.cursor()
res = cur.execute("select * from table").fetchall()
data = dict(zip([c[0] for c in cur.description], res[0]))

print(data)

欠点は.fetchall()、テーブルが非常に大きい場合、メモリ消費量が大幅に減少することです。しかし、数千行のテキストと数値列を扱う単純なアプリケーションの場合は、この単純な方法で十分です。

深刻なものについては、他の多くの回答で提案されているように、行ファクトリを調べる必要があります。

于 2019-12-29T21:36:31.753 に答える
0

わずか 3 行を使用する一般的な代替手段

def select_column_and_value(db, sql, parameters=()):
    execute = db.execute(sql, parameters)
    fetch = execute.fetchone()
    return {k[0]: v for k, v in list(zip(execute.description, fetch))}

con = sqlite3.connect('/mydatabase.db')
c = con.cursor()
print(select_column_and_value(c, 'SELECT * FROM things WHERE id=?', (id,)))

ただし、クエリが何も返さない場合は、エラーが発生します。この場合...

def select_column_and_value(self, sql, parameters=()):
    execute = self.execute(sql, parameters)
    fetch = execute.fetchone()

    if fetch is None:
        return {k[0]: None for k in execute.description}

    return {k[0]: v for k, v in list(zip(execute.description, fetch))}

また

def select_column_and_value(self, sql, parameters=()):
    execute = self.execute(sql, parameters)
    fetch = execute.fetchone()

    if fetch is None:
        return {}

    return {k[0]: v for k, v in list(zip(execute.description, fetch))}
于 2015-10-13T17:16:50.410 に答える