dict slice in python (translating perl to python)
B
execrable at gmail.com
Wed Sep 10 12:31:35 EDT 2008
for a long list, you could try:
result = [mydict[k] for k in mydict]
or [mydict[k] for k in mydict.keys()]
or [mydict[k] for k in mydict.iterkeys()]
this won't give you the same order as your code though, if you want them
sorted you can use the sorted function:
[mydict[k] for k in sorted(x)] (or sorted(x.etc))
hofer 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
>
More information about the Python-list
mailing list