Dictionary of tuples from query question

David Pratt fairwinds at eastlink.ca
Mon Nov 14 06:55:05 CET 2005


Hi.  I am interested in having results from a db query in the following 
form.

{1: (value0, value1, value2,), 2: (value0, value1, value2,), 3: 
(value0, value1, value2,)}

so I generate a dictionary of tuples (field values) dynamically so if I 
queried a table with five fields I would have five fields in my tuple 
and if I had 20 fields in my query, I would have 20 fields in my tuple, 
etc.

Note that the dict starts at 1 and not zero.  From the code below, the 
structure I have currently is:

{1: {0:value0, 1:value1, 2:value2}, 2: {0:value0, 1:value1, 2:value2}, 
3: {0:value0, 1:value1, 2:value2}}

My code so far. I guess my problem is how to generate a tuple 
dynamically when it is immutable?

Many thanks
David

cursor = db.cursor()
cursor.execute("""
	SELECT * FROM countries;
	""")
rows = cursor.fetchall()

vdict = {}
for row in range(len(rows)):
	col_dict = {}
	for col in range(len(rows[row])):
		value = rows[row][col]
		col_dict[col] = value
	vdict[row + 1] = col_dict
print vdict

	
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: text/enriched
Size: 1136 bytes
Desc: not available
URL: <http://mail.python.org/pipermail/python-list/attachments/20051114/c59a1746/attachment.bin>


More information about the Python-list mailing list