[Tutor] Pouring a list into a dictionary

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Mon Sep 29 19:40:17 EDT 2003



On Mon, 29 Sep 2003, Allen wrote:

> The answer to my last inquiry worked out to be this: (thanks for the
> suggestions)
>
> I have two lists (same length) and needed field ONE from list A
> (headings) be the key to the value of field ONE of list B (foundData).
> Iterate through these to create my dictionary.
>
> dataDict={}
> for k, v in map(None, headings, foundData):
>    dataDict[k]= v

Hi Allen,


Ah!  As of Python 2.3, there's another concise way of saying this:

###
dataDict={}
for k, v in map(None, headings, foundData):
   dataDict[k]= v
###



Using some of 2.3's new features, we can now say it this way:

###
dataDict = dict(zip(headers, foundData))
###


This takes advantage of two "builtins" that have been improved: 'dict()'
and 'zip()'.

    http://www.python.org/doc/lib/built-in-funcs.html#l2h-22
    http://www.python.org/doc/lib/built-in-funcs.html#l2h-78





> Next question: How to use %s formatting (I think) to access those
> key/value pairs in an sql insert statement. Here is what I need:
>
> for k, v in map(None, headings, foundData):
>    dataDic[k]= v
> sql = "replace into tablename %s values(%s)"
> crsr.execute(sql, (dataDict.keys(),dataDict.values()))


One way to do this is to move the crsr.execute() within the loop body
itself:

###
sql = "replace into tablename %s values (%s)"
for k, v in map(None, headings, foundData):      ## we can use zip()
    crsr.execute(sql, (k, v))
###


According to the DB-API 2.0 spec,

    http://www.python.org/peps/pep-0249.html

you can also call the executemany() method to do this operation on your
whole list of key/value pairs.  So you should be able to say:

###
sql = "replace into tablename %s values (%s)"
crsr.executemany(zip(headings, foundData))
###

Just to clear things up: In the code above, I subsituted map(None, ...)
with zip(), since zip() is a nice way to pairwise glue two sequences
together.




> The order does not really matter when the stuff is taken from the dict
> but the key/value order obviously makes a difference when presented.

Ah, then that's something you don't have to worry about!  Python does
guarantee that if we call keys() and values(), that the order should
correspond:

    http://www.python.org/doc/lib/typesmapping.html

Note 3 is the one that guarantees this for us.  Darn obscure, but possibly
useful to know.  *grin*



Good luck to you!




More information about the Tutor mailing list