Missing the functional mind set

Erik Max Francis max at alcyone.com
Sat Mar 3 14:22:30 EST 2001


Daniel Klein wrote:
> 
> The purpose of this code is to return a list of dictionary values sorted by
> key, resulting in 'templist'.
> 
> >>> d = {3: 'd', 2: 'b', 1: 'a', 0: 'z'}
> >>> templist = []
> >>> for n in range(len(d)):
>         templist.append(d[n])

Why not just:

>>> d = {3: 'd', 2: 'b', 1: 'a', 0: 'z'}
>>> templist = d.values()
>>> templist
['d', 'b', 'a', 'z']

> My question is, is there a 'functional' (or list comprehension)
> solution to
> this? I don't seem to have a sufficient grasp of functional
> programming as yet.

I don't think so.  The sort method sorts the list in place; it returns
None.  That being said, you can get what you want in two lines:

>>> d = {3: 'd', 2: 'b', 1: 'a', 0: 'z'}
>>> result = d.values()     
>>> result.sort()
>>> result
['a', 'b', 'd', 'z']

-- 
 Erik Max Francis / max at alcyone.com / http://www.alcyone.com/max/
 __ San Jose, CA, US / 37 20 N 121 53 W / ICQ16063900 / &tSftDotIotE
/  \ One completely overcomes only what one assimilates.
\__/ Andre Gide
    The laws list / http://www.alcyone.com/max/physics/laws/
 Laws, rules, principles, effects, paradoxes, etc. in physics.



More information about the Python-list mailing list