[Tutor] advice: making dictionary from two lists?
Michael P. Reilly
arcege@speakeasy.net
Wed, 16 May 2001 16:23:43 -0400 (EDT)
Benoit Dupire wrote
> Nice!!!!!!!!
> so, using your idea:
>
> class superDict(UserDict):
> def __init__(self, list1=[], list2=[]):
> self.data={}
> foo =map(operator.setitem, [self.data]*len(list1), list1, list2)
>
> not tested, but that should work....
>
> I was interested to see what the result is, if list2 is shorter than list1
>
> >>> labels = ('name', 'age', 'salary')
> >>>values = ('Monty', 42)
> >>> map(operator.setitem, [d]*len(labels), labels, values)
>
> Result...
>
> >>> 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.
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:
>>> d = {}
>>> l1 = ['eggs', 'spam', 'toast', 'ham']
>>> l2 = [1, 2, 3, 4, 5, 6]
>>> import operator
>>> for (n, v) in map(None, l1, l2):
... d[n] = v
...
>>> d
{'spam': 2, 'ham': 4, None: 6, 'eggs': 1, 'toast': 3}
>>> d[None]
6
>>>
The for loop lets you control this better than the operator.setitem
solution would. This is where the new (to 2.x) zip() might be useful.
-Arcege
--
+----------------------------------+-----------------------------------+
| Michael P. Reilly | arcege@speakeasy.net |