Dictionary from list?

Ignacio Vazquez-Abrams ignacio at openservices.net
Fri Oct 19 05:48:16 EDT 2001


On Fri, 19 Oct 2001, Michael Hudson wrote:

> Jim Correia <jim.correia at pobox.com> writes:
>
> > Suppose I have a list with an even number of elements in the form
> >
> > [key1, value1, key2, value2, key3, value3]
> >
> > If I were writing Perl I could write
> >
> > my %hash = @array;
> >
> > and it would do the coercion for me, and build the hash appropriately.
> >
> > I'm a python newbie.  I know how to do it "by hand" with a loop, but is
> > there a built in conversion operater that will let me do something
> > simply like the perl assignment?
>
> No.  Write the loop.
>
> (You could probably do something horrible with reduce, but don't).

No, I don't think that reduce() could help, although list comprehensions
might.

> I've never found myself needing to do this, but that may be because
> I'm not used to having a convenient way of going from
> [k1,v1,k2,v2,...] to a dict.

I don't know anything about Perl's internals (and not much about it's
externals either, but that's a different story ;) ), but it may be that Perl's
hash is simply an array in disguise, whereas in Python mappings and sequences
are discrete objects.

-- 
Ignacio Vazquez-Abrams  <ignacio at openservices.net>

   "As far as I can tell / It doesn't matter who you are /
    If you can believe there's something worth fighting for."
       - "Parade", Garbage





More information about the Python-list mailing list