dict slice in python (translating perl to python)

hofer blabla at dungeon.de
Thu Sep 11 17:48:52 CEST 2008


Thanks a lot for all your answers.

There's quite some things I learnt :-)

[v1,v2,v3] = ...
can be typed as
v1,v2,v3 = . . .

I also wasn't used to
map(myhash.get, ['one', 'two', 'two'])
itemgetter('one', 'one', 'two')(x)

I also didn't know
print "%(one)s\n%(two)s\n%(two)s" % mydict


The reason I'd like to have a short statement for above is, that this
is for me basically just
some code, to name and use certain fields of a hash in i given code
section.

The real example would be more like:

name,age,country = itemgetter('name age country'.split())(x) # or any
of my above versions

# a lot of code using name / age / country



thanks a gain and bye

H
On Sep 10, 5:28 pm, hofer <bla... at dungeon.de> 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.
>
> 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)





More information about the Python-list mailing list