[Tutor] map & lambda to create dictionary from lists?
Reisfeld, Brad CAR
Brad.Reisfeld@carrier.utc.com
Sat, 25 Aug 2001 07:30:01 -0400
Hi,
My preferred method for accomplishing this is quite simple:
>>> d={}
>>> keys = ('name', 'age', 'food')
>>> values = ('Monty', 42, 'spam')
>>> map(d.setdefault, keys, values)
['Monty', 42, 'spam']
>>> d
{'name': 'Monty', 'age': 42, 'food': 'spam'}
-Brad
=================================
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'}