Thread: A sort question
View Single Post
Old Mar 25th, 2008, 8:56 AM   #3
Ooble
I eat cake for breakfast.
 
Ooble's Avatar
 
Join Date: Jul 2004
Location: In my box.
Posts: 4,434
Rep Power: 9 Ooble is on a distinguished road
Re: A sort question

First of all, I think you're representing your dictionary wrongly. Don't you mean:
{ a:[7,8,9],
  b:[4,5,6],
  c:[1,2,3] }

You have to remember that a dictionary has no inherent order. That said, you can convert the dictionary into a tuple using the items or iteritems methods, which return a list of tuples and an iterator over said list respectively.

A bit of Googling found this interesting solution: http://www.python.org/dev/peps/pep-0265/

For a dictionary x, this will work:
sorted(x.iteritems(), key = lambda ( (_, value) ) : value)
This tells the sorted function to iterate over the list of tuples and to use the second part of the tuple as its sort key.

EDIT: Seems Sane beat me to it, though his method works differently.
__________________
Me :: You :: Them
Ooble is offline   Reply With Quote