Dictionary from list?

Michael Hudson mwh at python.net
Fri Oct 19 04:57:46 EDT 2001


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).

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.

Cheers,
M.

-- 
  After a heavy night I travelled on, my face toward home - the comma
  being by no means guaranteed.           -- paraphrased from cam.misc



More information about the Python-list mailing list