pythonsortingprettytable

Python prettytable Sort by Multiple Columns


I'm using PrettyTable to print data to the terminal in a nice table format. It's pretty easy to print it ordered by a single column.

from prettytable import PrettyTable

table = PrettyTable(["Name", "Grade"])
table.add_row(["Joe", 90])
table.add_row(["Sally", 100])
print table.get_string(sortby="Grade", reversesort=True)

>> Table with Sally on top, because her score is highest.

My trouble is I want to sort on two columns. In this surrogate case, I would want to print by grade, and then alphabetically if there was a tie.

table = PrettyTable(["Name", "Grade"])
table.add_row(["Joe", 90])
table.add_row(["Sally", 100])
table.add_row(["Bill", 90])
print table.get_string(sortby=("Grade","Name"), reversesort=True)

>> Doesn't work

The docs say that sort_key will allow me to write a function to accomplish this, but I haven't seen an actual implementation to work off.


Solution

  • You can call operator.itemgetter() as a sort_key value. Note that sortby still needs to be given for the sort_key to be applied:

    import operator
    from prettytable import PrettyTable
    
    
    table = PrettyTable(["Name", "Grade"])
    table.add_row(["Joe", 90])
    table.add_row(["Sally", 100])
    table.add_row(["Bill", 90])
    table.add_row(["Alice", 90])
    print table.get_string(sort_key=operator.itemgetter(1, 0), sortby="Grade")
    

    Prints:

    +-------+-------+
    |  Name | Grade |
    +-------+-------+
    | Alice |   90  |
    |  Bill |   90  |
    |  Joe  |   90  |
    | Sally |  100  |
    +-------+-------+