Missing the functional mind set

Mark Pilgrim f8dy at diveintopython.org
Sat Mar 3 14:04:46 EST 2001


in article mlb2at8ptrr7sh5dgq8qlk2201kquh6tfl at 4ax.com, Daniel Klein at
danielk at aracnet.com wrote on 3/3/01 1:08 PM:

> 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']
> 
> My question is, is there a 'functional' (or list comprehension) solution to
> this?

Since you explicitly asked for hints, not answers, here are some hints:
- AFAIK, the fastest way for me to sort things in Python is with the sort()
method of a list, because it's written in C and has been optimized by people
smarter than me.
- sort() modifies an existing list in place; it does not return a new list.
- sort() will sort a list of any type of object, not just simple datatypes.
For instance, if you have a list of tuples, sort() will perform a multi-key
sort, treating the first element of each tuple as the primary key, the
second element as the secondary key (to break ties where the first elements
are the same), and so forth.
- Dictionaries have an items() method that returns a list of tuples [(key1,
value1), (key2, value2), ...]
- Once you have a list of sorted key/value pairs, you can use a list
comprehension to pull out just the value from each pair.

You can do it in 3 lines using a list comprehension.  Or 5 lines using a for
loop.  Or 1 heinous-looking UNIX command line.  Your choice.

-M
You're smart; why haven't you learned Python yet?
http://diveintopython.org/




More information about the Python-list mailing list