dict slice in python (translating perl to python)

Terry Reedy tjreedy at udel.edu
Thu Sep 11 01:03:03 CEST 2008

hofer wrote:

> Let's take following perl code snippet:
> %myhash=( one  => 1    , two   => 2    , three => 3 );
> ($v1,$v2,$v3) = @myhash{qw(one two two)}; # <-- line of interest
> print "$v1\n$v2\n$v2\n";
> How do I translate the second line in a similiar compact way to
> python?
> Below is what I tried. I'm just interested in something more compact.

Python does not try to be as compact as Perl.  Pythoneers generally 
consider that a feature.  Anyway, the second Python version is 
asymtotically as compact as the Perl code, differing only by a small 
constant number of bytes while the code size grows.

> mydict={ 'one'   : 1    , 'two'   : 2    , 'three' : 3 }
> # first idea, but still a little too much to type
> [v1,v2,v3] = [ mydict[k] for k in ['one','two','two']]

The initial brackets add nothing.  "v1,v2,v3 =" does the same.
> # for long lists lazier typing,but more computational intensive
> # as  split will probably be performed at runtime and not compilation
> time

You have spent and will spend more time posting and reading than the 
equivalent extra computation time this will take with any normal 
exchange rate and computation usage.

> [v1,v2,v3] = [ mydict[k] for k in 'one two two'.split()]

This is a standard idiom for such things.  If it bothers you, type "'one 
two two'.split()" into an interactive window and 'in a blink' get 
['one', 'two', 'two'], which you can cut and paste into a program.

> print "%s\n%s\n%s" %(v1,v2,v3)

However, more that about 3 numbered variables in a Python program 
suggest the possibility of a better design, such as leaving the values 
in a list vee and accessing them by indexing.

Terry Jan Reedy

More information about the Python-list mailing list