pythonlistsorting

Sort a list of lists when one of the sort items is text month


I am trying to sort this list of lists by the year and then by month,I can get the years part sorted but am stuck when I try to do secondary sort by month. I have created a dict and a list to try to use to sort.

my code:

from operator import itemgetter

import pandas as pd

month_list = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
months = {
    'Jan': 0,
    'Feb': 1,
    'Mar': 2,
    'Apr': 3,
    'May': 4,
    'Jun': 5,
    'Jul': 6,
    'Aug': 7,
    'Sep': 8,
    'Oct': 9,
    'Nov': 10,
    'Dec': 11,
}
data = [['Sep', '2024', 112], ['Dec', '2022', 79], ['Apr', '2023', 114], ['Aug', '2024', 194], ['May', '2022', 140], ['Jan', '2023', 222]]

half_sorted = sorted(data, key=itemgetter(1))
input(half_sorted)

My Output so far:

[['Dec', '2022', 79], ['May', '2022', 140], ['Apr', '2023', 114], ['Jan', '2023', 222], ['Sep', '2024', 112], ['Aug', '2024', 194]]

Solution

  • import pandas as pd
    
    month_list = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]
    months = { 'Jan': 0, 'Feb': 1, 'Mar': 2, 'Apr': 3, 'May': 4, 'Jun': 5, 'Jul': 6, 'Aug': 7, 'Sep': 8, 'Oct': 9, 'Nov': 10, 'Dec': 11, }
    data = [['Sep', '2024', 112], ['Dec', '2022', 79], ['Apr', '2023', 114], ['Aug', '2024', 194], ['May', '2022', 140], ['Jan', '2023', 222]]
    
    sorted_data = sorted(data, key=lambda x: (int(x[1]), months[x[0]]))
    
    
    print(sorted_data)
    

    The code sorts the data list first by year (ascending) and then by the month's order using the months dictionary.