0 votes
1 view
in SQL by (22.4k points)

db = sqlite.connect("test.sqlite")

res = db.execute("select * from table")

With iteration, I get lists corresponding to the rows.

for row in res:

    print row

I can get the name of the columns

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

But is there some function or set to get dictionaries instead of a list?

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

or I have to do myself?

1 Answer

0 votes
by (40.3k points)

You can try using row_factory, like this:

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

Otherwise, follow the advice that's given right after this example in the docs:

If returning a tuple doesn’t suffice and you want name-based access to columns, then you should consider setting row_factory to the highly-optimized sqlite3.Row type. Row provides both index-based and case-insensitive name-based access to columns with almost no memory overhead. It will probably be better than your own custom dictionary-based approach or even a db_row based solution.

Related questions

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer
asked Jul 26 in SQL by Tech4ever (22.4k points)
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...