[Tutor] map & lambda to create dictionary from lists?

Lance E Sloan lsloan@umich.edu
Fri, 24 Aug 2001 09:09:04 -0400

The recent discussion of map and lambda coupled with a bit of ugly code
I wrote recently inspired me to learn more about these things.

What I've got are two sequences.  The first is a sequence of strings
that I want to use as the keys of a dictionary.  The second is a
sequence of objects (strings, numbers, whatever) that I want to use as
the values in the dictionary.  Of course, the two sequences have a
one-to-one correspondence.

Here's what I've come up with using map and lambda so far and I want to
know if it's Good:

    Python 2.0 (#1, Jan  8 2001, 10:18:58) 
    [GCC egcs-2.91.66 19990314 (egcs-1.1.2 release)] on sunos5
    Type "copyright", "credits" or "license" for more information.
    >>> d = {}
    >>> keys = ('name', 'age', 'food')
    >>> values = ('Monty', 42, 'spam')
    >>> junk = map(lambda k, v: d.update({k: v}), keys, values)
    >>> junk
    [None, None, None]
    >>> d
    {'name': 'Monty', 'age': 42, 'food': 'spam'}

Okay, so it works.  The list returned by map isn't all that useful,
other than maybe for finding out how many pairs were processed.  I feel
like I'm not using map the way it was intended.  Is this a Bad Thing?

More importantly, is there a better way to do this?  I'd rather not
reinvent the wheel with this.

What I'm actually going to use this for is to turn a row of data
fetched from an Oracle database using DCOracle's fetchone into a
dictionary.  DCOracle's cursor object has a description attribute
that's a tuple of tuples.  Each inner tuple contains the name of a
column, its data type, and other stuff.  So, I would probably invoke
map like this:

	junk = map(lambda k, v: d.update({k[0]: v}), csr.description, row)

I use k[0] because the very first element of the inner tuple is the
name of the column that I want to use as the key.

Lance E Sloan
Web Services, Univ. of Michigan: Full-service Web and database design,
development, and hosting.  Specializing in Python & Perl CGIs.
http://websvcs.itd.umich.edu/ - "Putting U on the Web"