[Python-Dev] Dict constructor

Jack Jansen Jack.Jansen@oratrix.com
Wed, 26 Jun 2002 22:30:43 +0200


On woensdag, juni 26, 2002, at 07:38 , Raymond Hettinger wrote:
>  To fix it, I found myself
> writing the same code over and over again:
>
>   def _toset(container):
>        return dict([(elem, True) for elem in container])
>
> This repeated dictionary construction exercise occurs in so many
> guises that it would be worthwhile to provide a fast, less magical
> looking approach.

I disagree on this being "magical", I tend to think of it as 
"Pythonic". If there is a reasonably easy to remember construct 
(such as this one: if you've seen it once you'll remember it) 
just use that, in stead of adding extra layers of functionality. 
Moreover, this construct has lots of slight modifications that 
are useful in slightly different situations (i.e. don't put True 
in the value but something else), and people will "magically" 
understand these if they've seen this one.

What I could imagine would be nice is a warning if you're doing 
inefficient "in" operations. But I guess this would have to be 
done in the interpreter itself (I don't think pychecker could do 
this, or could it?), and the definition of "inefficient" is 
going to be difficult ("if your program has done more than N1 in 
operations on a data structure with more than N2 items in it and 
these took an average of O(N1*N2/2) compares", and keep that 
information per object).
--
- Jack Jansen        <Jack.Jansen@oratrix.com>        
http://www.cwi.nl/~jack -
- If I can't dance I don't want to be part of your revolution -- 
Emma Goldman -