dict view to list

Terry Reedy tjreedy at udel.edu
Sat Mar 28 01:26:03 CET 2009

Luis Gonzalez wrote:
> Yes, I know the python approach is to use built-ins.
> But wouldn't it be cool if we could do mydict.values().tolist()
> instead?

Should we also give every collection a .toset(), .tofrozenset(), 
.totuple(), and .todict() method?  This way lies the madness of 
combinatorial explosion.

> It would be more regular and intuitive and readable from an OO point
> of view.

In my opinion, this is backwards.  From an OO point of view, instances 
of class X should be created by the constructor for that class.  That is 
where the knowledge of the intermal structure of class X instances 
belongs.  The principle of information hiding dictates that other 
classes should not know how to create an X.  On the other hand, 
collection classes should be iterable and know how to de-structure 
themselves. So list(iterable) operates by iterable providing an iterator 
that list uses to create an instance.  The stream of object provided by 
the iterator is the common means of transferring information.

> In my oppinion, this would be cleaner.

To me, the hypothetical

import operator
map(operator.attrgetter('tolist'), [[1,2,3], (1,2,3), 

is a lot dirtier than the current

map(list, [[1,2,3], (1,2,3), {1,2,3},{1:'a',2:'b',3:'c'}])

> Built-ins used like this look like an early decission made when
> designing an imperative language.

It is part of python basic design.  Functions used as functions can be 
passed as arguments to functions and used to operator on heterogeneous 
collections, as in the example above.

Terry Jan Reedy

More information about the Python-list mailing list