sort dictionary by value

Robin Thomas robin.thomas at starmedia.net
Wed Apr 11 12:17:11 EDT 2001


At 03:02 PM 4/11/01 +0000, bas.vangils at home.nl wrote:
>Hi everyone,
>
>I've been toying around with sorting a dictonary _by value_ for the last 
>couple
>of days. Using 'seqdict' from the ndict-thiny I found, I do just what I 
>want...
>at least, that's what I thought *sigh*.

Q: Can dictionaries be sorted?

A: No. Dictionaries have no concept of ordering of their items, such that 
the items can be "re-ordered" in the dictionary by sorting them.

Q: Can I retrieve all of the items in a dictionary and sort them?

A: Yes.

 >>> d  = some_big_dictionary()
 >>> i = d.items()
# sort by value
 >>> i.sort(lambda x,y: cmp(x[1],y[1]))
# sort by key
 >>> i.sort(lambda x,y: cmp(x[0],y[0]))

Q: I only want to use certain items from the dictionary, and sort those. Can I?

A: Yes. Retrieve those items, then sort as above.

 >>> d = some_big_dictionary()
 >>> keys = ('one', 'two', 'three', 'four')
 >>> items = []
 >>> for k in keys:
...     items.append( (k, d.get(k)) )
...
# sort by value
 >>> items.sort(lambda x,y: cmp(x[1],y[1]))

Q: But I really want to have a magical dictionary that orders its items and 
allows me to re-order the items inside the dictionary. Can I have that, please?

A: You must implement such an object yourself, and it's not as easy as you 
might think. Before you commit to implementing such an object, ask yourself 
if you really need it.


--
Robin Thomas
Engineering
StarMedia Network, Inc.
robin.thomas at starmedia.net





More information about the Python-list mailing list