dict slice in python (translating perl to python)
Nick Craig-Wood
nick at craig-wood.com
Fri Sep 12 12:36:42 EDT 2008
Steven D'Aprano <steven at REMOVE.THIS.cybersource.com.au> wrote:
> On Thu, 11 Sep 2008 03:36:35 -0500, Nick Craig-Wood wrote:
>
> > As an ex-perl programmer and having used python for some years now, I'd
> > type the explicit
> >
> > v1,v2,v3 = mydict['one'], mydict['two'], mydict['two'] # 54 chars
> >
> > Or maybe even
> >
> > v1 = mydict['one'] # 54 chars
> > v2 = mydict['two']
> > v3 = mydict['two']
> >
> > Either is only a couple more characters to type.
>
> But that's an accident of the name you have used. Consider:
>
> v1,v2,v3 = section_heading_to_table_index['one'], \
> section_heading_to_table_index['two'], \
> section_heading_to_table_index['two'] # 133 characters
>
> versus:
>
> v1,v2,v3 = [section_heading_to_table_index[k] for k in
> ['one','two','two']] # 75 characters
>
> It also fails the "Don't Repeat Yourself" principle, and it completely
> fails to scale beyond a handful of keys.
If you have more than a handful of keys then you have a different
problem (far too many local variables) with your code I think!
DRY is a good principle. I still prefer the 3 explicit assignments
though ;-)
> Out of interest, on my PC at least the list comp version is significantly
> slower than the explicit assignments. So it is a micro-optimization that
> may be worth considering if needed -- but at the cost of harder to
> maintain code.
>
> > 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
>
> That's a matter for argument. I find the list comprehension perfectly
> readable and comprehensible, and in fact I had to read your explicit
> assignments twice to be sure I hadn't missed something. But I accept that
> if you aren't used to list comps, they might look a little odd.
A matter of taste certainly!
--
Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick
More information about the Python-list
mailing list