473,385 Members | 1,359 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,385 software developers and data experts.

Remap Mysql tuple to dictionary

Pom
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
Sep 25 '06 #1
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>

Sep 25 '06 #2
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


Sep 25 '06 #3
Pom
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!!
Sep 25 '06 #4
Pom
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.
Sep 25 '06 #5
Pom
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!
Sep 26 '06 #6
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 ...

Sep 26 '06 #7
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>

Sep 26 '06 #8
Lawrence D'Oliveiro wrote:
yield dict(zip(Fields, NextRow))
the OP didn't ask for a field name =value mapping, though.

</F>

Sep 26 '06 #9
Fredrik Lundh wrote:
the OP didn't ask for a field name =value mapping, though.
footnote: but for those who want that, I strongly recommend using
something like Greg Stein's dtuple module:

http://aspn.activestate.com/ASPN/Coo...n/Recipe/81252
http://www.lyra.org/greg/python/dtuple.py

</F>

Sep 26 '06 #10
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?
Sep 26 '06 #11
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>

Sep 26 '06 #12
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...
Sep 26 '06 #13
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>

Sep 26 '06 #14
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.
Sep 26 '06 #15
Lawrence D'Oliveiro wrote:
SQL databases like MySQL are _designed_ for efficiency.
unlike the Python data types, you mean ?

</F>

Sep 26 '06 #16
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?
Sep 26 '06 #17
>
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
Sep 26 '06 #18
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
Sep 26 '06 #19
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

Sep 26 '06 #20
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

Sep 26 '06 #21

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

Sep 26 '06 #22
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>

Sep 26 '06 #23
> 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

Sep 26 '06 #24

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

Sep 26 '06 #25
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
Sep 26 '06 #26
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

Sep 26 '06 #27
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.
Sep 26 '06 #28

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

Similar topics

3
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,
50
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,...
9
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'},...
8
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...
4
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)))
4
by: laxmikiran.bachu | last post by:
Can we have change a unicode string Type object to a Tuple type object.. If so how ????
11
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,...
2
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....
3
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,...
1
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...
0
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...
0
isladogs
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...
0
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...
0
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,...
0
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...
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...
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...

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.