sorting a file

John Machin sjmachin at
Sun Jun 15 00:18:45 CEST 2008

On Jun 15, 2:00 am, jim-on-linux <inq1... at> wrote:
> On Saturday 14 June 2008 03:15, Beema
> shafreen wrote:
> > Hi all,
> > I have a file with three columns  i need
> > to sort the file with respect to the third
> > column. How do I do it uisng python. I
> > used Linux command to do this. Sort but i
> > not able to do it ? can any body ssuggest
> > me
> I have used this method to solve similar
> problems.
> This is a consept of how to do what you want,
> but you will have to work a little to get it
> right.
> You might try something like this;
> Dict = {}  ##create a dictionary
> make a list of all column3 values

Ummm this appears somewhat baroque .... try this:

Assuming the OP has arranged to read his data into a list of lists
"filedata" such that filedata[-1][2] is the data in the 3rd column of
the last row. Further assume that the data has just been read with
e.g. the csv module so all data is still in text form and may need
some conversion before comparison (otherwise e.g. a salary of 100000
would appear before a salary of 99999).

Suppose the 3rd column is a salary, without '$' and ',' in it.

Now let's look at the manual for the sort method. It gives us 2
options: a cmp function and a key function, with a strong hint that
key is better. So for each row, what do we want on sort on? It's the
numerical value of the 3rd item:

def sort_key_func(row):
   return float(row[2])

Then we can simply do:

All that remains is to write the contents of filedata to the output


More information about the Python-list mailing list