[Tutor] how to sort a dictionary by values

wormwood_3 wormwood_3 at yahoo.com
Wed Aug 8 05:58:39 CEST 2007

>>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).

Just curious: Is there a reason to use __getitem__() over itemgetter (used in the example in my reply)?

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

I think Shawn would want to leave off "reverse=True". The default is least to greatest, which is what he wanted, I think.

More information about the Tutor mailing list