Sort a list with a custom order in Python

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.

Leave a Comment