Explore Courses Blog Tutorials Interview Questions
0 votes
in SQL by (20.3k 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.7k 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
asked Jul 27, 2019 in SQL by Soni Kumari (40.7k points)
0 votes
1 answer
0 votes
1 answer
asked Jul 26, 2019 in SQL by Tech4ever (20.3k points)
0 votes
1 answer
asked Dec 12, 2020 in SQL by Appu (6.1k points)
0 votes
1 answer

Browse Categories