1
I’m using sqlite3 to record some data. However, by default, when a select is made, it returns the information as a list of tuples, which is considerably harder to work with than if they were dictionaries. Example:
>>> import sqlite3
>>> bd = sqlite3.connect('python.db')
>>> cursor = bd.cursor()
>>> cursor.execute('CREATE TABLE livro (titulo text, autor text)')
>>> cursor.execute('INSERT INTO livro VALUES (?, ?)', ('Manoel', 'Minha história'))
>>> cursor.execute('SELECT * FROM livro')
>>> livros = cursor.fetchall()
>>> livros
[('Manoel', 'Minha história')]
The most obvious solution I can think of would be:
>>> lista_livros = []
>>> for livro in livros:
>>> d = {'autor': livro[0], 'titulo': livro[1],}
>>> lista_livros.append(d)
But that way the code gets pretty big when there are too many columns. And that way, every time there’s any change in the columns, it would be necessary to change the code as well.
It is interesting to note that other À Dbs connectors, such as connectors to Mysql and Postgres have the "Dictcursor" that already does what is requested - however for sqlite3 it is not available.
– jsbueno