dict slice in python (translating perl to python)

Aaron "Castironpi" Brady castironpi at gmail.com
Thu Sep 11 14:00:44 EDT 2008


On Sep 11, 10:52 am, hofer <bla... at dungeon.de> wrote:
> On Sep 11, 10:36 am, Nick Craig-Wood <n... at craig-wood.com> wrote:
>
> >I'd type the explicit
>
> >  v1,v2,v3 = mydict['one'], mydict['two'], mydict['two'] # 54 chars > Either is only a couple more
> > characters to  type.  It is completely
> > explicit and comprehensible to everyone, in comparison to
>
> >   v1,v2,v3 = [ mydict[k] for k in ['one','two','two']] # 52 chars
> >   v1,v2,v3 = [ mydict[k] for k in 'one two two'.split()] # 54 chars
>
> > Unlike perl, it will also blow up if mydict doesn't contain 'one'
> > which may or may not be what you want.
>
> Is your above solution robust against undefined keys.
> In my example it would'nt be a problem. The dict would be fully
> populated, but I'm just curious.

If undefined keys aren't a problem, then there's a value you expect
from them.  Use

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

where default is the value you're expecting.



More information about the Python-list mailing list