Skip to content Skip to sidebar Skip to footer

"sort By X (ascending) Then By Y (descending)" For A Csv File In Python

So I have a csv file that I want to sort using 2 columns (basically the same idea in excel as 'sort by somecol then by anothercol'). Given that csvbody is a list of lists generated

Solution 1:

Since Python's sort is guaranteed to be stable, this should do what you want:

# First sort by secondary key
sortedcsv = sorted(csvbody, key=operator.itemgetter(anothercol, reverse=True)
# Then sort by primary key
sortedcsv = sorted(sortedcsv, key=operator.itemgetter(somecol))

Reference:

Post a Comment for ""sort By X (ascending) Then By Y (descending)" For A Csv File In Python"