473,785 Members | 2,209 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Fastest way to convert sql result into a dict or list ?

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', 's********@some thing.net'],
[2, 1, 'address','some thing stree'],
[2, 3, 'email','s***** ***@something.n et']]
the dict can be:
dict={1:['something street', '1111111111' ,
's********@some thing.net'],
2:['something street', '', 's********@some thing.net' ]}
or a list can be:
list=[[1,'something street', '1111111111' ,
's********@some thing.net'],
[2,'something street', '', 's********@some thing.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 ?
Oct 29 '08 #1
3 8104
On Oct 29, 9:35*pm, "rewo...@gmail. com" <rewo...@gmail. comwrote:
I'm trying to find the fastest way to convert an sql result into a
dict or list.
>>from collections import defaultdict
results = defaultdict(def aultdict)
for contact_id, field_id, field_name, value in sql_result:
... results[contact_id][field_id] = value
... results[contact_id][field_name] = value
...

This lets you reference things in a straightforward way:
>>results[1]['email']
'someth...@some thing.net'

If you'd prefer to use only the ids for reference:
>>results = defaultdict(def aultdict)
for contact_id, field_id, field_name, value in sql_result:
... results[contact_id][field_id] = (field_name, value)
...
>>results[1][1]
('address', 'something street')

Hope this helps.
Oct 29 '08 #2
re*****@gmail.c om 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', 's********@some thing.net'],
[2, 1, 'address','some thing stree'],
[2, 3, 'email','s***** ***@something.n et']]
the dict can be:
dict={1:['something street', '1111111111' ,
's********@some thing.net'],
2:['something street', '', 's********@some thing.net' ]}
or a list can be:
list=[[1,'something street', '1111111111' ,
's********@some thing.net'],
[2,'something street', '', 's********@some thing.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__.u pdate(dict(zip( names, data))

FIELDS = "A B C D".split()
sql = "SELECT %s FROM table" % ", ",join(FIEL DS)
curs.execute(sq l)
for data in curs.fetchall() :
row = recstruct(FIELD S, 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/

Oct 30 '08 #3
Dennis Lee Bieber wrote:
On Wed, 29 Oct 2008 04:35:31 -0700 (PDT), "re*****@gmail. com"
<re*****@gmail. comdeclaimed the following in comp.lang.pytho n:
>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', 's********@some thing.net'],
[2, 1, 'address','some thing stree'],
[2, 3, 'email','s***** ***@something.n et']]

Off-hand, field_ID and field_name are equivalent and only one would
be needed (either you know that "2" is a telnumber, or you just take the
name directly).
>I hope there is an easyest way to do something like this ??
any idea ?

Let the database do it?

select
c.contact_id as contact,
c.value as address,
t.value as telephone,
e.value as email
from thetable as c
inner join thetable as t
on c.contact_id = t.contact_id and c.field_id = 1 and t.field_id = 2
inner join thetable as e
on c.contact_id = e.contact_id and c.field_id = 1 and e.field_id= 3

If the join complains about the "= constant" clauses, try

select
c.contact_id as contact,
c.value as address,
t.value as telephone,
e.value as email
from thetable as c
inner join thetable as t
on c.contact_id = t.contact_id
inner join thetable as e
on c.contact_id = e.contact_id
where c.field_id = 1 and t.field_id = 2 and e.field_id = 3

(technically, the latter first finds all combinations

c.address, t.address, e.address
c.address, t.address, e.telephone
etc.

and then removes the results where c is not the address, t is not the
phone, and e is not the email; doing them on the joins should mean a
smaller intermediate result is generated)
You will lose contact information if you use an inner join and there are
contacts that lack fields (like contact #2 without a telephone number). Use
an outer join like in my (generated) sql to fix that and "distinct" to
suppress duplicate contact_id-s. The following should work with SQLite3:

select distinct
c.contact_id, a.value as address,
t.value as telnumber,
e.value as email
from contacts as c
left outer join contacts as a
on c.contact_id = a.contact_id and a.field_id=1
left outer join contacts as t
on c.contact_id = t.contact_id and t.field_id=2
left outer join contacts as e
on c.contact_id = e.contact_id and e.field_id=3

Peter
Oct 30 '08 #4

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

15
1678
by: john fabiani | last post by:
Hi, newbie question: PyPgSQL (postgres driver) returns a list (not a tuple O'Rielly states DBAPI returns a tuple) and most of the books describe how to work with tuples and dictionaries when working with a result set. Does anyone know of a paper or tutorial that explains a few ways to deal with result sets. Or if anyone knows of a module that will help (that I can study) - that would be just as helpful? TIA
16
23017
by: flyaflya | last post by:
a = "(1,2,3)" I want convert a to tuple:(1,2,3),but tuple(a) return ('(', '1', ',', '2', ',', '3', ')') not (1,2,3)
2
2025
by: shearichard | last post by:
Hi - I want to take something like ... lstIn = lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 10, 'LEA_AUTOID': 1000}) lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 11, 'LEA_AUTOID': 2000}) lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 11, 'LEA_AUTOID': 2001}) lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 11, 'LEA_AUTOID': 2003}) lstIn.append({'COM_AUTOID': 1, 'PRG_AUTOID': 12, 'LEA_AUTOID': 3000}) lstIn.append({'COM_AUTOID': 1,...
6
6116
by: Niyazi | last post by:
Hi all, What is fastest way removing duplicated value from string array using vb.net? Here is what currently I am doing but the the array contains over 16000 items. And it just do it in 10 or more minutes. 'REMOVE DUBLICATED VALUE FROM ARRAY +++++++++++++++++ Dim col As New Scripting.Dictionary Dim ii As Integer = 0
2
3631
by: Tom Grove | last post by:
I have a server program that I am writing an interface to and it returns data in a perl dictionary. Is there a nice way to convert this to something useful in Python? Here is some sample data: 200 data follow { Calendar = { Access = { anyone = lr;};
6
46191
by: buzzweetman | last post by:
Many times I have a Dictionary<string, SomeTypeand need to get the list of keys out of it as a List<string>, to pass to a another method that expects a List<string>. I often do the following: <BEGIN CODE> List<stringkeyNameList = new List<string>(); foreach (string keyName in this.myDictionary.Keys)
4
1366
by: Fulvio | last post by:
*********************** Your mail has been scanned by InterScan MSS. *********************** Hello, I'm poor in knoweledge of python, sorry. What's the fastest result between : if item in alist:
27
5153
by: comp.lang.tcl | last post by:
My TCL proc, XML_GET_ALL_ELEMENT_ATTRS, is supposed to convert an XML file into a TCL list as follows: attr1 {val1} attr2 {val2} ... attrN {valN} This is the TCL code that does this: set contents ]; close $fileID
11
8567
by: Prateek | last post by:
I have 3 variable length lists of sets. I need to find the common elements in each list (across sets) really really quickly. Here is some sample code: # Doesn't make sense to union the sets - we're going to do intersections later anyway l1 = reduce(operator.add, list(x) for x in l1) l2 = reduce(operator.add, list(x) for x in l2) l3 = reduce(operator.add, list(x) for x in l3)
0
9483
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10157
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10096
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9956
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8982
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6742
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5386
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5514
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4055
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.