Question: ```
db = sqlite.connect("test.sqlite")
res = db.execute("select * from table")

```

With iteration I get lists coresponding to the rows.

```
for row in res:
    print row

```

I can get name of the columns

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

```

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

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

```

or I have to do myself?

Answer: 
You could use [row\_factory](http://docs.python.org/library/sqlite3.html#sqlite3.Connection.row_factory), as in the example in the docs:

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

```

or 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, 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.
> 
> 
> 

Here is the code for this second solution:

```
con = sqlite3.connect(…)
con.row_factory = sqlite3.Row   #   add this row
cursor = con.cursor()

```
A generic alternative, using just three lines

```
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,)))

```

But if your query returns nothing, will result in error. In this case...

```
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))}

```

or

```
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))}

```