dict slice in python (translating perl to python)

Jon Clements joncle at googlemail.com
Wed Sep 10 18:20:33 CEST 2008


On 10 Sep, 16:28, hofer <bla... at dungeon.de> wrote:
> Hi,
>
> 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.
>
> 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']]
>
> # for long lists lazier typing,but more computational intensive
> # as  split will probably be performed at runtime and not compilation
> time
> [v1,v2,v3] = [ mydict[k] for k in 'one two two'.split()]
>
> print "%s\n%s\n%s" %(v1,v2,v3)
>
> thanks for any ideas

Another option [note I'm not stating it's preferred, but it would
appear to be closer to some syntax that you'd prefer to use....]

>>> from operator import itemgetter
>>> x = { 'one' : 1, 'two' : 2, 'three' : 3 }
>>> itemgetter('one', 'one', 'two')(x)
(1, 1, 2)

hth
Jon.




More information about the Python-list mailing list