Sort list by month order and add the missing month

I’ve my month_list that I got using most_common() from collection module that looks like this:

[('October', 3744), ('September', 3329), ('November', 3072), ('March', 2630), ('February', 2268), ('June', 2046), ('December', 1959), ('August', 1880), ('May', 1567), ('July', 1289), ('April', 1237), ('January', 1155)]

What I want is index the list with the correct months order, I’ve tried like this:

month_index  = ['January', 'February',' March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']

month_list.index(month_index)

But I get this error

ValueError: ['January', 'February', ' March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] is not in list

Also I’ve another list month_list2 where January is totally missing, but when sorting I’d like to have something like this:

[('January','NA'), ('February', 568), ('March', 3481)...]

is it possible? Thanks!

Answer

To sort list, you should use sort with index being its key:

month_list.sort(key = lambda item:month_index.index(item[0]))

.. but, you also want to add missing items. So you’d better convert month_list to a dict, and access dict item with NA being its default value:

month_dict = dict(month_list)
month_list = [(month, month_dict.get(month, 'NA')) for month in month_index]