[Tutor] map & lambda to create dictionary from lists?
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Fri, 24 Aug 2001 09:36:57 -0700 (PDT)
On Fri, 24 Aug 2001, 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:
>
> 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.
I'm not sure if this is better; tell me what you think of this approach:
###
def itemsToDict(items):
dict = {}
for key, value in items:
dict[key] = value
keys = ('name', 'age', 'foo')
values = ('Monty', 42, 'spam')
zipped_up_values = zip(keys, values)
dict = itemsToDict(zipped_up_values)
###
itemsToDict() seems to be a useful function; I use it all the time, but I
always have lingering doubts that I've reinvented the wheel somehow.
As a somewhat related note: map(), too, is special cased to do "zipping"
if we give it None in the function argument.
###
>>> map(None, [1, 2, 3], [4, 5, 6])
[(1, 4), (2, 5), (3, 6)]
###
Hope this helps!