1

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 from the csv file, the way I have it right now that I found from this question is sortedcsv = sorted(csvbody, key = operator.itemgetter(somecol, anothercol)) The issue is that I want to sort by somecol in ascending order and anothercol in descending order. Is there a way to do this (even better, in one line)?

I know that I could do sortedcsv = sorted(csvbody, key = operator.itemgetter(somecol, anothercol), reverse = True) but then it sorts both of them in descending order. Then I tried doing two lines:

sort1 = sorted(csvbody, key = operator.itemgetter(somecol))
sort2 = sorted(sort1, key = operator.itemgetter(anothercol), reverse = True))

However this doesn't work because the second sort just overrides the first sort (it's as if I went into excel and sorted in descending order just by "anothercol")

If you need me to include more information please let me know.

Community
  • 1
  • 1
davzaman
  • 823
  • 2
  • 10
  • 20

1 Answers1

2

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:

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • Oh man I missed that in the docs, thanks for sharing! I probably should have tried reversing the order of the statements. I'm a little confused as to why reversing the order worked. Do you think you could point me to something that explains why it worked the second way but not the first? – davzaman Aug 26 '14 at 02:13
  • 1
    In addition to the reference I list in the answer, http://en.wikipedia.org/wiki/Sorting_algorithm#Stability – Robᵩ Aug 26 '14 at 02:16
  • That card image on the right is a really good example. I understand why the second way works but not the first now (at least I believe I do! haha). Thank you very much again for the spot-on help! – davzaman Aug 26 '14 at 02:26