dict slice in python (translating perl to python)

hofer blabla at dungeon.de
Wed Sep 10 11:28:43 EDT 2008


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




More information about the Python-list mailing list