Python Sort One List According to Another List

First, I’d make colorOrder a mapping:

colorMap = {c: i for i, c in enumerate(colorOrder)}

Now sorting becomes a bit easier with colorMap.get

sorted(tupleList, key=lambda tup: colorMap.get(tup[1], -1))

This puts things not in the map first. If you’d rather add them last, just use a really big number:

sorted(tupleList, key=lambda tup: colorMap.get(tup[1], float('inf')))

Leave a Comment