473,424 Members | 1,804 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,424 software developers and data experts.

Select as dictionary...

Hi..
I am using python with postgresql.
And i have a query :

aia.execute("SELECT id, w from list")
links=aia.fetchall()
print links

and result
[(1, 5), (2,5).......] (2 million result)

I want to see this result directly as a dictionary:

{1: 5, 2: 5 .....}

How do i select in this format ?

I'm sorry my bad english.

King Regards...

Oct 1 '07 #1
17 2395
Besturk.Net Admin a écrit :
Hi..
I am using python with postgresql.
And i have a query :

aia.execute("SELECT id, w from list")
links=aia.fetchall()
print links

and result
[(1, 5), (2,5).......] (2 million result)

I want to see this result directly as a dictionary:

{1: 5, 2: 5 .....}

How do i select in this format ?
IIRC, postgres' db-api connector (well, at least one of them - I don't
know which one you're using) has a DictCursor. You should find all you
want to know in the relevant doc.

FWIW:
http://www.initd.org/tracker/psycopg/wiki/PsycopgTwoFaq

HTH
Oct 1 '07 #2
On Mon, Oct 01, 2007 at 06:32:07AM -0700, Besturk.Net Admin wrote regarding Select as dictionary...:
>
aia.execute("SELECT id, w from list")
links=aia.fetchall()
print links

and result
[(1, 5), (2,5).......] (2 million result)

I want to see this result directly as a dictionary:

{1: 5, 2: 5 .....}

How do i select in this format ?
Try this:

aia.execute("SELECT id, w from list")
links=aia.fetchall()
linkdict = dict()
for k,v in links:
linkdict[k] = v
print linkdict
Cheers,
Cliff
Oct 1 '07 #3
On Mon, 01 Oct 2007 09:57:46 -0400, J. Clifford Dyer wrote:
On Mon, Oct 01, 2007 at 06:32:07AM -0700, Besturk.Net Admin wrote
regarding Select as dictionary...:
>>
aia.execute("SELECT id, w from list") links=aia.fetchall()
print links

and result
[(1, 5), (2,5).......] (2 million result)

I want to see this result directly as a dictionary:

{1: 5, 2: 5 .....}

How do i select in this format ?
Try this:

aia.execute("SELECT id, w from list")
links=aia.fetchall()
linkdict = dict()
for k,v in links:
linkdict[k] = v
print linkdict
Besides using the already pointed out DB adapters, you can easily
transform a list of items into a dictionary with the `dict` constructor::
>>links = [(1, 5), (2, 5), (3, 10)]
dict(links)
{1: 5, 2: 5, 3: 10}

Stargaming
Oct 1 '07 #4
On 2007-10-01 15:32, Besturk.Net Admin wrote:
Hi..
I am using python with postgresql.
And i have a query :

aia.execute("SELECT id, w from list")
links=aia.fetchall()
print links

and result
[(1, 5), (2,5).......] (2 million result)

I want to see this result directly as a dictionary:

{1: 5, 2: 5 .....}

How do i select in this format ?
You can easily convert the above list to a dictionary:

d = dict(links)

--
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source (#1, Oct 01 2007)
>>Python/Zope Consulting and Support ... http://www.egenix.com/
mxODBC.Zope.Database.Adapter ... http://zope.egenix.com/
mxODBC, mxDateTime, mxTextTools ... http://python.egenix.com/
__________________________________________________ ______________________

:::: Try mxODBC.Zope.DA for Windows,Linux,Solaris,MacOSX for free ! ::::
eGenix.com Software, Skills and Services GmbH Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
Registered at Amtsgericht Duesseldorf: HRB 46611
Oct 1 '07 #5
"J. Clifford Dyer" <jc*@sdf.lonestar.orgwrote:
aia.execute("SELECT id, w from list")
links=aia.fetchall()
linkdict = dict()
for k,v in links:
linkdict[k] = v
print linkdict
Wouldn't it be simpler just to do:

aia.execute("SELECT id, w from list")
linkdict=dict(aia.fetchall())

even better would be to use an iterator to avoid fetching the entire
resultset as a list.
Oct 1 '07 #6
On Mon, 2007-10-01 at 09:57 -0400, J. Clifford Dyer wrote:
On Mon, Oct 01, 2007 at 06:32:07AM -0700, Besturk.Net Admin wrote regarding Select as dictionary...:

aia.execute("SELECT id, w from list")
links=aia.fetchall()
print links

and result
[(1, 5), (2,5).......] (2 million result)

I want to see this result directly as a dictionary:

{1: 5, 2: 5 .....}

How do i select in this format ?
Try this:

aia.execute("SELECT id, w from list")
links=aia.fetchall()
linkdict = dict()
for k,v in links:
linkdict[k] = v
print linkdict
Improvement 1: Use the fact that dict can be initialized from a sequence
of key/value pairs:

aia.execute("SELECT id, w from list")
linkdict = dict(aia.fetchall())

Improvement 2: Use an iterator instead of reading all rows into memory:

aia.execute("SELECT id, w from list")
linkdict = dict(iter(aia.fetchone,None))

--
Carsten Haese
http://informixdb.sourceforge.net
Oct 1 '07 #7
On Mon, 2007-10-01 at 15:50 +0200, Bruno Desthuilliers wrote:
Besturk.Net Admin a écrit :
I want to see this result directly as a dictionary:

{1: 5, 2: 5 .....}

How do i select in this format ?

IIRC, postgres' db-api connector (well, at least one of them - I don't
know which one you're using) has a DictCursor.
That would return the results as a list of dictionaries like this:

[{'id':1, 'w':5}, {'id':2, 'w':5}, ...]

--
Carsten Haese
http://informixdb.sourceforge.net
Oct 1 '07 #8
linkdict = dict(iter(aia.fetchone,None))

And by the way, that line can be shortened to "linkdict=dict(aia)" if
the cursor object supports the iterator protocol, but that's not a
mandatory feature in DB-API v2. The longer form is guaranteed to work
with any DB-API v2 compliant implementation.

--
Carsten Haese
http://informixdb.sourceforge.net
Oct 1 '07 #9
On Mon, Oct 01, 2007 at 10:12:04AM -0400, Carsten Haese wrote regarding Re: Select as dictionary...:
>
On Mon, 2007-10-01 at 09:57 -0400, J. Clifford Dyer wrote:
>
Try this:

aia.execute("SELECT id, w from list")
links=aia.fetchall()
linkdict = dict()
for k,v in links:
linkdict[k] = v
print linkdict

Improvement 1: Use the fact that dict can be initialized from a sequence
of key/value pairs:

aia.execute("SELECT id, w from list")
linkdict = dict(aia.fetchall())
This is only an improvement if the SQL query remains a list of 2-tuples. If the OP wants to add more values, the more verbose version allows for easier extensibility.

for k,v1,v2 in links:
linkdict[k] = (v1, v2)

Of course even better would be not to have to add variables, so maybe:

for link in links:
linkdict[link[0]] = link[1:],

which changes the output format somewhat, but keeps the access by dict keyed to the DB id.
Improvement 2: Use an iterator instead of reading all rows into memory:

aia.execute("SELECT id, w from list")
linkdict = dict(iter(aia.fetchone,None))
Agreed. A much better solution.

Cheers,
Cliff
Oct 1 '07 #10
J. Clifford Dyer a écrit :
On Mon, Oct 01, 2007 at 03:50:59PM +0200, Bruno Desthuilliers wrote regarding Re: Select as dictionary...:
>IIRC, postgres' db-api connector (well, at least one of them - I don't
know which one you're using) has a DictCursor. You should find all you
want to know in the relevant doc.

Correct me if I'm wrong, but I think the DictCursor would output the following:

[{'id': 1, 'value': 5}, {'id': 2, 'value': 5}, ...]

But the OP wanted one dict with IDs as keys:

{1: 5, 2: 5, ...}
Hmmm... I did answer too fast, indeed. Thanks for pointing that out.

Oct 1 '07 #11
On 1 Ekim, 18:13, Bruno Desthuilliers <bruno.
42.desthuilli...@wtf.websiteburo.oops.comwrote:
J. Clifford Dyer a écrit :
On Mon, Oct 01, 2007 at 03:50:59PM +0200, Bruno Desthuilliers wrote regarding Re: Select as dictionary...:
IIRC, postgres' db-api connector (well, at least one of them - I don't
know which one you're using) has a DictCursor. You should find all you
want to know in the relevant doc.
Correct me if I'm wrong, but I think the DictCursor would output the following:
[{'id': 1, 'value': 5}, {'id': 2, 'value': 5}, ...]
But the OP wanted one dict with IDs as keys:
{1: 5, 2: 5, ...}

Hmmm... I did answer too fast, indeed. Thanks for pointing that out.
Very very very thanks to everybody.
I'm a new user in this group and you are wonderfull persons :)

Oct 1 '07 #12
Also if i need a list id what can i do ?

aia.execute("SELECT id, w from list")
links=aia.fetchall()

I want to..

idlist=[1, 2, 3] ( I don't want to use FOR and APPEND because the
query have 2 million result and i want to speed)

Oct 1 '07 #13
Abandoned wrote:
Also if i need a list id what can i do ?

aia.execute("SELECT id, w from list")
links=aia.fetchall()

I want to..

idlist=[1, 2, 3] ( I don't want to use FOR and APPEND because the
query have 2 million result and i want to speed)
It will always return a list of tuples, so even if you'd do
select id from list
you'd end up with

[(1,), ...]

But you shouldn't bother - a simple

idlist = [v[0] for v in links]

should do it. Because this program shows that it takes only a split-second
to process 2 million list-entries and create a new one:

import time

two_million = range(2000000)

start = time.time()
[i * 2 for i in two_million]

used = time.time() - start

print used
Need 0.8 seconds on my machine. So - don't bother.

Diez
Oct 1 '07 #14
On Mon, 2007-10-01 at 10:13 -0700, Abandoned wrote:
Also if i need a list id what can i do ?

aia.execute("SELECT id, w from list")
links=aia.fetchall()

I want to..

idlist=[1, 2, 3] ( I don't want to use FOR and APPEND because the
query have 2 million result and i want to speed)
The canonical replacement for a for/append loop is a list comprehension:

idlist = [x[0] for x in links]

HTH,

--
Carsten Haese
http://informixdb.sourceforge.net
Oct 1 '07 #15
wang frank wrote:
>
Hi,

I need to help to install these two packages on debian. I want to know
what packages do I need to? I have installed fftw3,fftww2, sfftw2,
atlas. Did I miss anything? In what way I can install an optimized numpy
and scipy, since my project is very big and speed is important.
Be sure to install the -dev packages for each of the above as well as
python-dev. You will probably also want to install the CPU-specific versions of
ATLAS, too (like atlas3-sse2). If you *really* need speed, I recommend building
a more recent release of ATLAS yourself especially if you have a CPU released in
the last couple of years. The 3.7 series has seen a lot of improvements over the
3.6 released in Debian.

If you can live with the packaged versions of ATLAS and FFTW, then you might
also be able to live with the packaged python-numpy and python-scipy. They are
somewhat older than the current release, but that shouldn't be too bad.

If you want to build numpy and scipy yourself and you need more specific help,
please join us on scipy-user with your questions.

http://www.scipy.org/Mailing_Lists

--
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
that is made terrible by our own mad attempt to interpret it as though it had
an underlying truth."
-- Umberto Eco

Oct 1 '07 #16
Abandoned <be*****@gmail.comwrote:
( I don't want to use FOR and APPEND because the
query have 2 million result and i want to speed)
How many times do you plan on doing this? On my system I just timed adding
2 million elements to a dictionary: it took 0.35 seconds. Appending 2
million elements to a list took 0.43 seconds.

Unless you really do need to repeat this operation many many many times
then just write the obvious code instead of wasting your (and our) time
trying to micro-optimise.
Oct 2 '07 #17
Abandoned wrote:
Also if i need a list id what can i do ?

aia.execute("SELECT id, w from list")
links=aia.fetchall()

I want to..

idlist=[1, 2, 3] ( I don't want to use FOR and APPEND because the
query have 2 million result and i want to speed)
It may not be practical for your algorithm, but I want to point out that
at this sort of query size it's much better (when you can) to repeatedly
call the execution cursor's fetchmany() method repeatedly. This avoids
having to allocate sufficient memory space to hold the whole query's output.

regards
Steve
--
Steve Holden +1 571 484 6266 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://del.icio.us/steve.holden

Sorry, the dog ate my .sigline

Oct 3 '07 #18

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

Similar topics

1
by: none | last post by:
or is it just me? I am having a problem with using a dictionary as an attribute of a class. This happens in python 1.5.2 and 2.2.2 which I am accessing through pythonwin builds 150 and 148...
9
by: Kevin | last post by:
Hi, I am getting a syntax error Microsoft VBScript compilation error '800a03ea' Syntax error On the code below. The error references the "End Select" line Can anyone help me with what I am...
1
by: john wright | last post by:
I have a dictionary oject I created and I want to bind a listbox to it. I am including the code for the dictionary object. Here is the error I am getting: "System.Exception: Complex...
4
by: toglez | last post by:
Hi all! I use PyQt4 and Python to create a program to display numbers from a file in a QTable Widget, select various columns from the table and then display the selected columns in a new table. ...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
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...
0
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...
0
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,...
0
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...

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.