Match each key with the desired priority:
key_precedence = dict((x, n) for n, x in enumerate(string_list))
Then sort by priority:
object_list.sort(key=lambda x: key_precedence[x.key])
To handle keys that cannot be in string_list:
default = -1 # put "unknown" in front default = sys.maxint # put "unknown" in back object_list.sort(key=lambda x: key_precedence.get(x.key, default))
If string_list is short (e.g. 10 or fewer elements), you can simplify:
object_list.sort(key=lambda x: string_list.index(x.key))
However, this is too important for large string_list strings.
source share