Dictionary from list?

Rich Harkins rharkins at thinkronize.com
Fri Oct 19 15:38:38 CEST 2001

Here's one (albeit ugly) possibility using list comprehensions and a
sufficiently new Python:

# Setup variables

# Here's the money line...
[d.__setitem__(l[i],l[i+1]) for i in range(0,len(l),2)]

It is trading one type of loop for another but it will work.  I did some
performance analysis and it does turn out that using a list comprehension
here is slower than using a loop, not to mention less readable to new
Pythonists.  I recommend the loop form myself, it's easy to read and it's
fast enough to do the job.


> -----Original Message-----
> From: python-list-admin at python.org
> [mailto:python-list-admin at python.org]On Behalf Of Jim Correia
> Sent: Friday, October 19, 2001 9:18 AM
> To: python-list at python.org
> Subject: Re: Dictionary from list?
> 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
> --
> http://mail.python.org/mailman/listinfo/python-list

More information about the Python-list mailing list