Missing the functional mind set

Steve Purcell stephen_purcell at yahoo.com
Sun Mar 4 09:36:35 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])
> 
> >>> templist
> ['z', 'a', 'b', 'd']

The problem is that sorting a list can't be done in a functional way.

Either of the following is vaguely functional, though:

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


or

	>>> d = {3: 'd', 2: 'b', 1: 'a', 0: 'z'}
	>>> stuff = d.items()
	>>> stuff.sort()
	>>> map(lambda i: i[1], stuff)
	['z', 'a', 'b', 'd']

The second is probably more efficient.

-Steve

-- 
Steve Purcell, Pythangelist
Get testing at http://pyunit.sourceforge.net/
Get servlets at http://pyserv.sourceforge.net/
"Even snakes are afraid of snakes." -- Steven Wright




More information about the Python-list mailing list