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

Roeland Rengelink r.b.rigilink@chello.nl
Fri, 24 Aug 2001 20:27:48 +0200


Hi Lance,

Lance E Sloan wrote:
> 
> 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:
> 

Hmm, No, it isn't ;) Relying on side-effects is generally a bad idea.
Two months from now you'll read that code and wonder why you're building
a list of junk.

How about this:

def dict_from_items(items)
    '''Build dict from list of items'''
    dict = {}
    for key, val in items:
        dict[key] = value
    return dict

d = dict_from_items(zip(key_list, value_list))

A nice little function that does exactly what it says it does.

About your DB example. It's probably a good idea to spend some time to
do try some more advanced approaches.

How about something like:

class DBEntry:
    def __init__(self, *args):
        ...assign args to appropriate attributes...
    def process(self):
        ...process myself...

processed_entry_list
for data in cursor.fetch_all():
    entry_list.append(DBEntry(*data).process())


Use several different DBEntry classes, usually one for each different
csr_description signature in your code. You can then put the code that
you'll write to process entries in methods of each DBEntry class. Before
you know it you'll be on your to full-fledged OO programming. Believe me
Pythons OO programming paradigm is much more powerful than its
functional programming paradigm.

Hope this helps,

Roeland

-- 
r.b.rigilink@chello.nl

"Half of what I say is nonsense. Unfortunately I don't know which half"