Dictionary from list?

Jim Correia correia at barebones.com
Fri Oct 19 09:17:54 EDT 2001


In article <u8ze8vwhh.fsf at python.net>, Michael Hudson <mwh at python.net> 
wrote:

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

That's unfortunate - a simple assignment would be better.  In the 
simplest case of my usage, the loop (while ultra short) could be 50% of 
the code.

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

The particular situation is the python implementation is going to be a 
command line script.  The calling convention for this script is to pass 
arguments on the command line in key value pairs.  The perl 
implementation looks like (in the simplest case)

my %args = @ARGV;

foreach(keys %args)
{
   print("$_: $args{$_}\n");
}

And it would be called from the command line as

perl myScript.pl name fred age 23 occupation "gravel worker"

I'd like to implement the script with the same calling conventions in 
python, and have an "easy" (typing wise, not conceptually, but I guess 
I'll have to write a reusable function) way to take the arguments on the 
command line and turn them into a dictionary.

Jim



More information about the Python-list mailing list