>>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
----------------------------
Hi Shawn,I was not sure how to do this either, but some digging revealed a very handing cookbook recipe on just this! (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/304440) So, here is an example of it working in the Python interpreter: ============== Python 2.5.1 (r251:54863, May 2 2007, 16:56:35) [GCC 4.1.2 (Ubuntu 4.1.2-0ubuntu4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> dict = {'a':21.3, 'b':32.8, 'c':12.92} >>> from operator import itemgetter >>> # This will print the dict, sorted by value: ... >>> print sorted(dict.items(), key=itemgetter(1)) [('c', 12.92), ('a', 21.300000000000001), ('b', 32.799999999999997)] ============== So just add that import, and use sorted() as I showed above, and you should be good to go.
_______________________________________________ Tutor maillist - [email protected] http://mail.python.org/mailman/listinfo/tutor
