Josh_Fokis
Josh_Fokis

Reputation: 99

Sqlite query to python dictionary

I have searched the docs and SO and could not find anything to resolve my issue. I am trying to call a select from my sqlite database and add it to a dictionary with the columns as keys. When I do this it returns a row for each column/key. It is has 14 columns and if I only have 4 rows it repeats for each one. This was the first attempt

columns = [desc[0] for desc in cursor.description]
results = []
for row in r:
    Summary = {}
    items = zip(columns, row)
    for (items, values) in items:
        Summary[items] = row
        results.append(Summary)

Then I also tried the row_factory as given in the docs. That didn't work. My end goal is to be able to print out to a text file verticly by using

for x in results:
    print x[name]
    print x[email]
    etc

Any help is appreciated

Upvotes: 0

Views: 2234

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121266

You are creating your dictionary incorrectly. Use:

for row in r:
    summary = dict(zip(columns, row))
    results.append(summary)

instead.

Your code sets the whole row sequence as the value for each key in Summary, instead of the individual column value, then appending that same dictionary to the results list for each column key..

Upvotes: 3

Related Questions