shawn bright wrote:
> hello there all,
> i am wondering how to sort a dictionary that i have by values.
> And i also need to sort them from greatest to least
> like if i have a dictionary
> 
> d = {'a':21.3, 'b':32.8, 'c': 12.92}
> 
> how could i sort these from least to greatest
> so that the order would turn out
> b,a,c

You can use d.__getitem__ as the key function for a sort of the keys. 
__getitem__() is the special method that is called for indexing a 
dictionary (or a list).

In [24]: d = {'a':21.3, 'b':32.8, 'c': 12.92}
In [26]: sorted(d.keys(), key=d.__getitem__, reverse=True)
Out[26]: ['b', 'a', 'c']

More on sorting here:
http://personalpages.tds.net/~kent37/kk/00007.html

Kent

_______________________________________________
Tutor maillist  -  Tutor@python.org
http://mail.python.org/mailman/listinfo/tutor

Reply via email to