Hello
I want to convert a Mysql resulset to a dictionary.
I made some code myself, and want to ask you if I do this the right way.
def remapmysql(a):
return (a[0], (a[1:]))
def test_map():
count = 100000 # count of simulated records
l1 = range(0, count)
l2 = range(count , 2 * count )
l3 = range(2 * count, 3 * count )
z1 = zip(l1, l2, l3) # simulate a mysql resultset
d1 = dict(map(remapmysql,z1))
return d1 27 2792
Pom wrote:
I want to convert a Mysql resulset to a dictionary.
that is, you want to convert an array of (key, value, ...) tuples to a
dictionary containing key: (value, ...) pairs, right ?
I made some code myself, and want to ask you if I do this the right way.
def remapmysql(a):
return (a[0], (a[1:]))
def test_map():
count = 100000 # count of simulated records
l1 = range(0, count)
l2 = range(count , 2 * count )
l3 = range(2 * count, 3 * count )
z1 = zip(l1, l2, l3) # simulate a mysql resultset
d1 = dict(map(remapmysql,z1))
return d1
looks fine to me.
if you care about performance, and is using a recent Python, you could
try doing
d1 = dict((row[0], row[1:]) for row in z1)
instead, and see if that runs faster (this uses a generator expression
instead of a callback and a full list).
</F>
def remapmysql(a):
return (a[0], (a[1:]))
def test_map():
count = 100000 # count of simulated records
l1 = range(0, count)
l2 = range(count , 2 * count )
l3 = range(2 * count, 3 * count )
z1 = zip(l1, l2, l3) # simulate a mysql resultset
d1 = dict(map(remapmysql,z1))
return d1
I'm not sure the map() is needed, as it could just be
>>d1 = dict((row[0], row[1:]) for row in z1)
which worked in my tests.
However either seems to work fairly well.
-tkc
Fredrik Lundh wrote:
if you care about performance, and is using a recent Python, you could
yes i do ;-)
try doing
d1 = dict((row[0], row[1:]) for row in z1)
instead, and see if that runs faster (this uses a generator expression
instead of a callback and a full list).
</F>
I changed it and it saves me some time so I leave it like that!
with 100000 test records:
>>>
dict+map (1, 2, 3) -{1: (2, 3)}: 1.343 seconds.
dict+gen-expr (1, 2, 3) -{1: (2, 3)}: 0.861 seconds.
>>>
dict+map (1, 2, 3) -{1: (2, 3)}: 1.397 seconds.
dict+gen-expr (1, 2, 3) -{1: (2, 3)}: 0.943 seconds.
with 500000 test records:
>>>
dict+map (1, 2, 3) -{1: (2, 3)}: 13.297 seconds.
dict+gen-expr (1, 2, 3) -{1: (2, 3)}: 8.335 seconds.
>>>
dict+map (1, 2, 3) -{1: (2, 3)}: 14.548 seconds.
dict+gen-expr (1, 2, 3) -{1: (2, 3)}: 9.793 seconds.
>>>
thank you!!
Tim Chase wrote:
>def remapmysql(a): return (a[0], (a[1:]))
def test_map(): count = 100000 # count of simulated records l1 = range(0, count) l2 = range(count , 2 * count ) l3 = range(2 * count, 3 * count ) z1 = zip(l1, l2, l3) # simulate a mysql resultset
d1 = dict(map(remapmysql,z1))
return d1
I'm not sure the map() is needed, as it could just be
>>d1 = dict((row[0], row[1:]) for row in z1)
which worked in my tests.
However either seems to work fairly well.
-tkc
thank you!!
changed it, see previous post.
Dennis Lee Bieber wrote:
It might be more economical to perform the conversion while fetching
the data:
mdict = {}
for rec in crsr:
mdict[rec[0]] = rec[1:]
I didn't think of that. I just took the fetchall() from my first
version (where I looped through the tuples, which was very slow)
I just dropped the .fetchall() part, and as you said: it works fine,
with 1 copy less. (but it doesn't save me time)
dict((int(row[0]), row[1:]) for row in cursor)
thanks!
In message <2r*********************@phobos.telenet-ops.be>, Pom wrote:
I want to convert a Mysql resulset to a dictionary.
Here's a function that does this one row at a time:
def GetEachRecord(TableName, Fields, Condition, Values, Extra = "") :
"""generator which does an SQL query which can return 0 or more
result rows, yielding each record in turn as a mapping from
field name to field value. TableName can be a single table name,
or a comma-separated list of names for a join. Extra allows
specification of order/group clauses."""
Cursor = sql.conn.cursor() # modify this as appropriate
Cursor.execute \
(
", ".join(Fields)
+
" from "
+
TableName
+
" where "
+
Condition
+
" "
+
Extra,
Values
)
while True :
NextRow = Cursor.fetchone()
if NextRow == None :
Cursor.close()
raise StopIteration
#end if
yield dict(zip(Fields, NextRow))
#end while
#end GetEachRecord
You'd use this something like
for Link in GetEachRecord(...) :
... Link[fieldname] ... blah-blah ...
Dennis Lee Bieber wrote:
Your remap operation will create a dictionary using the first field
as the key, and the rest of the fields as a list identified by that
key.... COPY 3
the tuple-to-dictionary conversion mostly shuffles pointers around,
though; it's not a full copy of all the data in the result set.
</F>
Lawrence D'Oliveiro wrote:
yield dict(zip(Fields, NextRow))
the OP didn't ask for a field name =value mapping, though.
</F>
In message <ma**************************************@python.o rg>, Fredrik
Lundh wrote:
Lawrence D'Oliveiro wrote:
> yield dict(zip(Fields, NextRow))
the OP didn't ask for a field name =value mapping, though.
What other kind of mapping could you produce?
Lawrence D'Oliveiro wrote:
What other kind of mapping could you produce?
and here we go again. how about reading the code the OP posted, or the
first few followups?
</F>
In message <ef**********@lust.ihug.co.nz>, I wrote:
In message <ma**************************************@python.o rg>, Fredrik
Lundh wrote:
>Lawrence D'Oliveiro wrote:
>> yield dict(zip(Fields, NextRow))
the OP didn't ask for a field name =value mapping, though.
What other kind of mapping could you produce?
All right, sorry, looks like they want to load the entire table into RAM and
key it off the first field. Kind of defeats the point of having SQL, but
there you go...
Lawrence D'Oliveiro wrote:
Kind of defeats the point of having SQL, but there you go...
there are plenty of reasons to use Python data structures instead of the
SQL engine for data crunching. especially if you care about efficiency.
</F>
In message <ma**************************************@python.o rg>, Fredrik
Lundh wrote:
Lawrence D'Oliveiro wrote:
Kind of defeats the point of having SQL, but there you go...
there are plenty of reasons to use Python data structures instead of the
SQL engine for data crunching. especially if you care about efficiency.
I think you have something else in mind when you say "efficiency", from what
I'm thinking of.
SQL databases like MySQL are _designed_ for efficiency.
Lawrence D'Oliveiro wrote:
SQL databases like MySQL are _designed_ for efficiency.
unlike the Python data types, you mean ?
</F>
In message <ma**************************************@python.o rg>, Fredrik
Lundh wrote:
Lawrence D'Oliveiro wrote:
SQL databases like MySQL are _designed_ for efficiency.
unlike the Python data types, you mean ?
Did I say it was unlike anything?
>
SQL databases like MySQL are _designed_ for efficiency.
Efficiency with respect to what? That statement is plain wrong. They are
designed for a pretty general case of data storage efficiency, in the
domain of relational algebra. And for a lot of use-cases, they offer a good
ratio of ease-of-use, speed and reliability and the overhead they
introduce.
But there are lots of cases where hand-tailored data structures - in python
as well as in C - are way better suited. Think of graph representations for
example, especially for reachability queries and the like. Does google use
ORACLE (or whatever DB) for their index? Nope.
So - without knowing the usecase,
"""
All right, sorry, looks like they want to load the entire table into RAM and
key it off the first field. Kind of defeats the point of having SQL, but
there you go...
"""
is a pretty strong thing to say.
Diez
On 9/26/06, Lawrence D'Oliveiro <ld*@geek-central.gen.new_zealandwrote:
All right, sorry, looks like they want to load the entire table into RAM and
key it off the first field. Kind of defeats the point of having SQL, but
there you go...
Keeping an in-memory cache of small, unchanging, frequently-read
tables is a very common, and often very effective performance tweak in
database driven systems.
--
Cheers,
Simon B, si***@brunningonline.net
Lawrence D'Oliveiro wrote:
In message <ma**************************************@python.o rg>, Fredrik
Lundh wrote:
>>Lawrence D'Oliveiro wrote:
SQL databases like MySQL are _designed_ for efficiency.
unlike the Python data types, you mean ?
Did I say it was unlike anything?
Can you please stop this incessant carping? c.l.py used to be a fun
place to hang out.
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden
Lawrence D'Oliveiro wrote:
In message <2r*********************@phobos.telenet-ops.be>, Pom wrote:
>>I want to convert a Mysql resulset to a dictionary.
Here's a function that does this one row at a time:
def GetEachRecord(TableName, Fields, Condition, Values, Extra = "") :
"""generator which does an SQL query which can return 0 or more
result rows, yielding each record in turn as a mapping from
field name to field value. TableName can be a single table name,
or a comma-separated list of names for a join. Extra allows
specification of order/group clauses."""
Cursor = sql.conn.cursor() # modify this as appropriate
Cursor.execute \
(
", ".join(Fields)
+
" from "
+
TableName
+
" where "
+
Condition
+
" "
+
Extra,
Values
)
while True :
NextRow = Cursor.fetchone()
if NextRow == None :
Cursor.close()
raise StopIteration
#end if
yield dict(zip(Fields, NextRow))
#end while
#end GetEachRecord
You'd use this something like
for Link in GetEachRecord(...) :
... Link[fieldname] ... blah-blah ...
This is a spectacularly bad (non-)solution to the original problem. It
also shows a fine disregard for readability requirements. I suppose you
are using a generator to avoid data duplication, but for 100,000 records
this could be regarded as a premature optimisation on modern computers.
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden
Steve Holden wrote:
>
Can you please stop this incessant carping? c.l.py used to be a fun
place to hang out.
Hey, Steve, don't let it get to you. It's still 98% fun.
I am reminded of a spoof Latin motto from the days of my youth -
NIL ILLEGITIMO CARBORUNDUM
Translation available on request.
Frank Millman
Frank Millman wrote:
I am reminded of a spoof Latin motto from the days of my youth -
NIL ILLEGITIMO CARBORUNDUM
isn't that usually written
Illegitimi non carborundum
?
or is that just due to differences between british latin and american latin ?
</F>
> NIL ILLEGITIMO CARBORUNDUM
>
isn't that usually written
Illegitimi non carborundum
or is that just due to differences between british latin and
american latin ?
Wouldn't those differences make it
"carbourundum" vs.
"carborundum" respectively?
:*)
(however, yes, dredging my grade-school Latin, I believe Fredrik
is correct in the common ordering of the phrase, though I can't
vouch for the declension of "illegitimi" vs. "illegitimo")
-tkc
Fredrik Lundh wrote:
Frank Millman wrote:
I am reminded of a spoof Latin motto from the days of my youth -
NIL ILLEGITIMO CARBORUNDUM
isn't that usually written
Illegitimi non carborundum
?
or is that just due to differences between british latin and american latin ?
</F>
or my bad memory - my youth was a long time ago :-)
Frank
On 9/26/06, Fredrik Lundh <fr*****@pythonware.comwrote:
Frank Millman wrote:
I am reminded of a spoof Latin motto from the days of my youth -
NIL ILLEGITIMO CARBORUNDUM
isn't that usually written
Illegitimi non carborundum
According to the Wikipedia, neither is actually correct latin -
<http://en.wikipedia.org/wiki/Illegitimi_non_carborundum- though I
think you are right about which form is the more common.
or is that just due to differences between british latin and american latin ?
American Latin? Is that Lingua::Romana::Perligata?
--
Cheers,
Simon B, si***@brunningonline.net
Frank Millman wrote:
Fredrik Lundh wrote:
>>Frank Millman wrote:
>>>I am reminded of a spoof Latin motto from the days of my youth -
NIL ILLEGITIMO CARBORUNDUM
isn't that usually written
Illegitimi non carborundum
?
or is that just due to differences between british latin and american latin ?
</F>
or my bad memory - my youth was a long time ago :-)
You were lucky, you *had* a youth [... etc.]
regards
Steve
--
Steve Holden +44 150 684 7255 +1 800 494 3119
Holden Web LLC/Ltd http://www.holdenweb.com
Skype: holdenweb http://holdenweb.blogspot.com
Recent Ramblings http://del.icio.us/steve.holden
In message <ma**************************************@python.o rg>, Steve
Holden wrote:
I suppose you are using a generator to avoid data duplication, but for
100,000 records this could be regarded as a premature optimisation on
modern computers.
I was using a generator to avoid loading all those 100,000 records into
memory at once. This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics
by: Jinming Xu |
last post by:
Sorry for the previous message. It's really a simple question and I have
solved it myself.
Thanks,
Jinming
------------------------------------------------------------------------
Hi Folks,
|
by: Will McGugan |
last post by:
Hi,
Why is that a tuple doesnt have the methods 'count' and 'index'? It
seems they could be present on a immutable object.
I realise its easy enough to convert the tuple to a list and do this,...
|
by: Odd-R. |
last post by:
I have a dictionary, and I want to convert it to a tuple,
that is, I want each key - value pair in the dictionary
to be a tuple in a tuple.
If this is the dictionary {1:'one',2:'two',3:'three'},...
|
by: Derick van Niekerk |
last post by:
I have found many posts that deal with writing a dictionary to MySQL in
a blob field - which I can't imagine why anybody would want to do it.
I want to write each element of a dictionary onto a...
|
by: bg_ie |
last post by:
Hi,
I have the following tuple -
t = ("one","two")
And I can build a dictionary from it as follows -
d = dict(zip(t,(False,False)))
|
by: laxmikiran.bachu |
last post by:
Can we have change a unicode string Type object to a Tuple type
object.. If so how ????
|
by: montyphyton |
last post by:
Recently, I got into a debate on programming.reddit.com about
what should happen in the following case:
Currently, Python raises an error *and* changes the first element of
the tuple. Now,...
|
by: hall.jeff |
last post by:
Before the inevitable response comes, let me assure you I've read
through the posts from Guido about this. 7 years ago Guido clearly
expressed a displeasure with allowing these methods for tuple....
|
by: bruce |
last post by:
hi guys/gals...
got a basic question that i can't get my hands around.
i'm trying to programatically create/use a list/tuple (or whatever the right
phrase in pyton is!!)
basically,...
|
by: CloudSolutions |
last post by:
Introduction:
For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
|
by: Faith0G |
last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
|
by: isladogs |
last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM).
In this session, we are pleased to welcome former...
|
by: ryjfgjl |
last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
|
by: taylorcarr |
last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
|
by: ryjfgjl |
last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
|
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
|
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...
|
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...
| |