[Tutor] how to sort a dictionary by values
Luke Paireepinart
rabidpoobear at gmail.com
Wed Aug 8 08:21:07 CEST 2007
wormwood_3 wrote:
>>> 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.
>
It wouldn't have taken you very long to check to see what he wanted :)
To save you time ;) he did want them in decreasing order.
-Luke
More information about the Tutor
mailing list