[Tutor] sorting by values in dict

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Thu Nov 13 14:23:44 EST 2003



On Thu, 13 Nov 2003, Gabriel Cooper wrote:

> >Is there a way to sort a dictionary by values?
> >
> You can do this:
>
>  >>> x = { 'file1':10000, 'file2':10000, 'file3':5000 }
>  >>> y = x.keys()
>  >>> y.sort()
>  >>> for key in y:
>     print str(key)+", "+ str(x[key])
>
> file1, 10000
> file2, 10000
> file3, 5000
>
>
> It's not pretty, but it works.


Hi Gabriel,


Be careful about fitting a solution to a particular example.  *grin*


This would work if Paul wanted to sort by the file names --- but he wants
to sort on the file sizes.  So if we have something like:

    d = {'a' : 2,
         'b' : 7,
         'c' : 1,
         'd' : 8}


we want to be able to sort it so that we get the key-value pairs in the
descending order:

    ('d', 8)
    ('b', 7)
    ('a', 2)
    ('c', 1)


Hope this helps!




More information about the Tutor mailing list