Search code examples
pythonsortingcsvprettytable

sorting list of list containing datetime.date in increasing/decreasing order to create pretty table/csv file


I have a list of lists containing datetime object.

table_of_list= [[name, email, address, details, date_last_contacted], 
 [u'Jane Doe', u'jdoe@abc.com', u'sillybilly', u'dodo', datetime.date(2016, 11, 1)]
 [u'John Doe', u'jedoe@abc.com', u'123 house',u'random', dateTime.date(2016,10,1)]
 [].....
]

I am populating this list of lists, so that I can utilize this to do two things:

  • create a pretty table using prettyTable module
  • use this to create a .csv file

Problem:

I need to organize the way the rows are being displayed sorted by the date_last_contacted order in both pretty table and csv. Pretty table sort is not working for me maybe because I have a header. But not entirely sure. I am new to python, not sure how the lambda thing works, but can i some how sort the list of lists before utilizing it to create .csv file or pretty table.

In short, How can I sort the lists within the table_of_list in the most pythonic way?


Solution

  • You can use sorted function where you set key to a lambda function that returns the last element - to sort by the last element.

    We take the first row of the original table as a header and then add the rest of the rows, which are sorted.

    sorted_table = [table_of_list[0]]
    sorted_table.extend(sorted(table_of_list[1:], key=lambda row: row[-1]))