[Tutor] Re: sorting by values in dict
Andrei
project5 at redrival.net
Thu Nov 13 04:50:38 EST 2003
Paul Tremblay wrote on Thu, 13 Nov 2003 01:52:31 -0500:
> Is there a way to sort a dictionary by values?
A dictionary is by definition unsorted.
> My problem involves a simple script that sorts files by size.
>
> I make dictionary that looks like this:
>
> {'file1': 10000,
> 'file2' : 10000,
> file3' : 5000,
> }
You'll then have to convert this back to a list of tuples of the form
(size, filename), and then use the sort() method of the list, e.g.:
>>> files = [(1000, 'file2'), (2000, 'file1'), (900, 'file3')]
>>> files.sort()
>>> files
[(900, 'file3'), (1000, 'file2'), (2000, 'file1')]
--
Yours,
Andrei
=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5 at jnanqbb.ay. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq
gur yvfg, fb gurer'f ab arrq gb PP.
More information about the Tutor
mailing list