[Tutor] Re: sorting by values in dict

Paul Tremblay phthenry at earthlink.net
Fri Nov 14 02:47:58 EST 2003


On Thu, Nov 13, 2003 at 10:50:38AM +0100, Andrei wrote:
> 
> 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')]
> 

Ah, thanks. Thanks everyone else, too. 

Instead of making a dictionary to begin with, I simply will make a list
of tupples and sort. I didn't know you could use sort with a list of
tupples. That does the trick.


Paul

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

What is this? So a robot can't read this, right? But how do you decode
it? 


> 
> 
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor

-- 

************************
*Paul Tremblay         *
*phthenry at earthlink.net*
************************



More information about the Tutor mailing list