list_to_dict()

Martin Maney maney at pobox.com
Fri Jan 17 22:09:05 EST 2003


Peter Abel <p-abel at t-online.de> wrote:
> 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}

It is something like that, but the difference is sort of crucial.  For
the dictionary in your example, the source would be the single sequence

(('zero',0),('one',1),('two',2)('three',3))

Except that in practice, the key may be more than one field of the
nested sequences, as may the value.  So this doesn't reduce to a simple
dict(zip(...)) for any simple '...'

Besides, the dict() constructor seems not to exist prior to 2.2, and at
this time I still need most of my code to coexist with 2.1. 
Furthermore, when I ran some simple benchmarks, calling a separate
function ran significantly faster than an inline dict(zip(...)) for the
small (five to ten items) cases I'm most frequently building.  I think
I emailed the test proggy home before I left the lab - have to look for
it tomorrow.

Here's the bare sketch:

def dzip(keys, values):
    res = {}
    for k,v in zip(keys, values):
        res[k] = v
    return res

foo = dzip(field_names, field_values)

runs faster than

foo = dict(zip(field_names, field_values))

for cases where there are a few to a few tens of names & values.  Hmmm,
just occurred to me that, although I tried making local bindings for
other things, I never did that to dict or zip...

Okay, definitely need to repoen this can of worms... later.




More information about the Python-list mailing list