list_to_dict()
Peter Abel
p-abel at t-online.de
Fri Jan 17 03:08:33 EST 2003
maney at pobox.com wrote in message news:<b06v5g$auj$2 at wheel2.two14.net>...
> Skip Montanaro <skip at pobox.com> wrote:
> >
> > maney> def list_to_dict(aList, key_indexes, value_indexes):
> > ...
> >
> > In 2.3 (and somewhat earlier I believe), you can call the dict() type like
> > so:
> >
> > >>> dict([("one", 1), ("two", 2)])
> > {'two': 2, 'one': 1}
>
> Which is a little bit like, but not usefully since the key is neither
> always the first item nor necessarily a single item in the source
> records.
>
> > You can, of course, smash your keys and values lists together using zip():
>
> Oh yeah, I do that quite a bit, too (though not in the program that
> gave rise to dict_from_list).
>
> >
> > >>> zip(("one", "two"), (1, 2))
> > [('one', 1), ('two', 2)]
>
> So for the current use I'd have something like
>
> theDict = dict(zip([(r[1],r[2]) for r in aList],
> [(r[0],r[2],r[3]) for r in alist]))
>
> Hmmmm. I can't say it looks like an improvement over the simple loop
> to my eyes. If anything it's buried the distinguishing features - the
> original list and the lists of indexes - under a slightly greater
> weight of scaffolding.
>
> There's some food for thought about related uses here, though. Thanks,
> Skip!
Sorry, when i didn't read the thread quite exactly,
but I think your basic problem is something like this, which can
be easily solved.
I'm using PYTHON 2.2.2:
>>> l1=['zero','one','two','three']
>>> l2=range(5)
>>> l1
['zero', 'one', 'two', 'three']
>>> l2
[0, 1, 2, 3, 4]
>>> di=dict(zip(l1,l2))
>>> di
{'zero': 0, 'three': 3, 'two': 2, 'one': 1}
>>>
Regards
Peter
More information about the Python-list
mailing list