[Tutor] advice: making dictionary from two lists?
Benoit Dupire
bdupire@seatech.fau.edu
Wed, 16 May 2001 17:04:30 -0400
"Michael P. Reilly" wrote:
> Benoit Dupire wrote
> > >>> labels = ('name', 'age', 'salary')
> > >>>values = ('Monty', 42)
> > >>> map(operator.setitem, [d]*len(labels), labels, values)
> > >>> d
> > {'age': 42, 'name': 'Monty', 'salary': None}
>
> This is nice, but realize that the for loop as been fairly well optimized
> and the above will create an unnecessary list. And it doesn't give you
> the control you might need.
>
I agree with you. I would also add that the operator.setitem makes it much more
difficult to understand the algorithm. it's not very readable...
>
> You already see that it extends the second list with None values.
> But if the second list is longer than the first, you'll get a key of
> None with the last value in the second list:
Actually Python returns an exception if list1 is shorter than list2 with the
other solution (operator.setitem). This is IMHO better than creating a key of
None.
-----------
>>> labels = ('name', 'age')
>>> values = ('Monty', 42, 5)
>>> d={}
>>> map(operator.setitem, [d]*len(labels), labels, values)
Traceback (innermost last):
File "<pyshell#165>", line 1, in ?
map(operator.setitem, [d]*len(labels), labels, values)
TypeError: object does not support item assignment
-------------
But, as you mentionned it, zip is even better
>>> labels = ('name', 'age')
>>> values = ('Monty', 42, 5)
>>> zip(values, labels)
[('Monty', 'name'), (42, 'age')]
Benoit