dict slice in python (translating perl to python)

Steven D'Aprano steven at REMOVE.THIS.cybersource.com.au
Thu Sep 11 11:05:47 CEST 2008

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


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.

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.


More information about the Python-list mailing list