Sorting csv files using python

Publicado em: 25 Novembro 2020
no canal de: IMSRS
8,330
76

This is a short video on how to sort a "comma separated values file" aka csv file using python.
I've used csv module for this.
Why it is difficult to sort a csv file in python?
Basically csv file is read using csv.reader() method.
This method returns the csv class object. When we convert the csv class object into a list then the resultant list will be "list of lists".
Here comes the main problem. We know how to sort a list using sort method which belongs to list class, but when it comes to list of lists sorting becomes trickier as the value we have to sort according to, will not be readily available in the list. It will be inside the list's list. I know it sounds crazy just look at the list of list given below:
x = [ ["Rollno 1", "ABC 1", 69], [ "Rollno 2", "ABC 2", 78], [ "Rollno 3", "ABC 3", 58 ] ]
if we use "x.sort()" the result would be :
[['Rollno 1', 'ABC 1', 69], ['Rollno 2', 'ABC 2', 78], ['Rollno 3', 'ABC 3', 58]]
That's why sort() is just not enough.
We have to use a key which returns the value through which we want to sort the file. this can be done by using:

i)
import operator
x = sorted(x, key=operator.itemgetter(3), reverse=True)# or just use x.sort( key=operator.itemgetter(3), reverse=True)
ii) you can replace key by
key=lambda row: row[3]

So by the following method we can sort x:
step (i)
x.sort(key = lambda l: l[-1], reverse = True)
step (ii)
x
[['Rollno 2', 'ABC 2', 78], ['Rollno 1', 'ABC 1', 69], ['Rollno 3', 'ABC 3', 58]]

references:
https://stackoverflow.com/questions/2...
code:
https://github.com/theunhackable/sort...

Meet me on::
  / srsp1116  
https://github.com/theunhackable/


Nesta página do site você pode assistir ao vídeo on-line Sorting csv files using python duração hora minuto segundo em boa qualidade , que foi baixado pelo usuário IMSRS 25 Novembro 2020, compartilhe o link com seus amigos e conhecidos, no youtube este vídeo já foi visto 8,330 vezes e gostou 76 espectadores. Boa visualização!