list_to_dict()

maney at pobox.com maney at pobox.com
Thu Jan 16 13:54:40 EST 2003


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!




More information about the Python-list mailing list