Bhargav Panth Bhargav Panth - 4 months ago 6x
Python Question

How do I sort records which are like `a | b | c | 8` and `n | 8 | p | 4` in Python?

I have a CSV file containing values like

a | b | c | 8
n | 8 | p | 4
as so on. I would like to know as to how do I sort them considering the last element in each row as the index?

Ex: sorted order for the above would be
n | 8 | p | 4
a | b | c | 8

I am using Python csv reader to read the file and want to apply Quick sort. I split the CSV with
but not quite sure how do I proceed from here. Or if splitting isn't the correct thing to do? Can someone shed some light as to how I should be doing it?


If you have a list of lists you could use the pre built sorting function, which should be faster than anything you can implement yourself.

There is a command in sort which then does exactly what you want:

sorted(yourArray, key=lambda x: x[3])
#sort yourArray by the 4th value in every list

So what I would do is:

  • Read csv and split it with ' | '
  • Save all lines you read in a list
  • use the above function which returns a new list (it is not in place sorting)


Just saw the new comments, and if you want to add new entries and keep your List sorted, you should look into the bisec module.

It is used for inserting values into an already sorted list, but does not support the key operator. They explain how to use it for lists of your type in the last paragraph of the link.