Fastest way to convert sql result into a dict or list ?
Steve Holden
steve at holdenweb.com
Thu Oct 30 00:40:11 EDT 2008
rewonka at gmail.com wrote:
> Hello,
>
> I'm trying to find the fastest way to convert an sql result into a
> dict or list.
> What i mean, for example:
> my sql result:
> contact_id, field_id, field_name, value
> sql_result=[[1, 1, 'address', 'something street'],
> [1, 2, 'telnumber', '1111111111'],
> [1, 3, 'email', 'something at something.net'],
> [2, 1, 'address','something stree'],
> [2, 3, 'email','something at something.net']]
> the dict can be:
> dict={1:['something street', '1111111111' ,
> 'something at something.net'],
> 2:['something street', '', 'something at something.net' ]}
> or a list can be:
> list=[[1,'something street', '1111111111' ,
> 'something at something.net'],
> [2,'something street', '', 'something at something.net' ]]
>
> I tried to make a dict, but i think it is slower then make a list, and
> i tried the "one lined for" to make a list, it's look like little bit
> faster than make a dict.
>
> def empty_list_make(sql_result):
> return [ [line[0],"", "", ""] for line in sql_result]
>
> than fill in the list with another for loop.
> I hope there is an easyest way to do something like this ??
> any idea ?
Why not go for full attribute access? The following code is untested,
yada yada yada.
class recstruct:
def __init__(self, names, data):
self.__dict__.update(dict(zip(names, data))
FIELDS = "A B C D".split()
sql = "SELECT %s FROM table" % ", ",join(FIELDS)
curs.execute(sql)
for data in curs.fetchall():
row = recstruct(FIELDS, data)
print row.A, row.B ...
regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC http://www.holdenweb.com/
More information about the Python-list
mailing list