Search code examples
pythonlistsortingpython-2.7

Sort a list with a custom order in Python


I have a list

mylist = [['123', 'BOOL', '234'], ['345', 'INT', '456'], ['567', 'DINT', '678']]

I want to sort it with the order of 1. DINT 2. INT 3. BOOL

Result:

[['567', 'DINT', '678'], ['345', 'INT', '456'], ['123', 'BOOL', '234']]

I've seen other similar questions in stackoverflow but nothing similar or easily applicable to me.


Solution

  • SORT_ORDER = {"DINT": 0, "INT": 1, "BOOL": 2}
    
    mylist.sort(key=lambda val: SORT_ORDER[val[1]])
    

    All we are doing here is providing a new element to sort on by returning an integer for each element in the list rather than the whole list. We could use inline ternary expressions, but that would get a bit unwieldy.