[Tutor] Adding items from a cursor to a dict?
Alan Gauld
alan.gauld at btinternet.com
Mon Nov 12 10:15:13 CET 2012
On 12/11/12 08:29, Khalid Al-Ghamdi wrote:
> Hi all,
> How would you go about adding items from a cursor to a dictionary?
>
> i tried this but to no avail:
>
> >>> cur.execute('select * from schedule limit 10')
> <sqlite3.Cursor object at 0x0112CE60>
> >>> for i in range(len(cur.fetchall())):
> d[i]=cur.fetchall()[i]
>
The second fetchall() won't return anything because you already fetched
all there was to fetch in the first call.
But why would you want a dictionary indexed by sequence number? You'd be
better off with a list, which is what fetchall() gives you..
The normal pattern would be
for row in cur.fetchall():
d[ row[0] ] = row # assuming row[0] is the desired key
or similar.
--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
More information about the Tutor
mailing list