sorting a dictionary?

Tony Meyer t-meyer at ihug.co.nz
Mon Mar 21 21:13:00 EST 2005


> mydict = {'the':358, 'they':29, 'went':7, 'said':65}
> 
> Is there an easy to sort this dictionary and get a
> list like the following (in decreasing order)?
> 
> the   358
> said  65
> they  29
> went  7

The dictionary's keys and values are lists, which can be sorted, so you can
just use that.  This would be simple to do if you were sorting on the keys,
but is a bit more complicated trying to sort on the values (since you can't
lookup a key from a value).

You can do this by converting the items (not just values) to a list and then
sorting, for example:

>>> mydict = {'the':358, 'they':29, 'went':7, 'said':65}
>>> mydict_as_list = list(mydict.items())
>>> mydict_as_list.sort(key=lambda p:p[1], reverse=True)
>>> for k,v in mydict_as_list:
... 	print k, v
... 	
the 358
said 65
they 29
went 7

There are no doubt faster and cleverer ways to do this (and ways that don't
use a lambda), but this works...

=Tony.Meyer




More information about the Python-list mailing list