How can I sort a list, according to where its elements appear in another list?

The most efficient way would be to create a map from word to order:

ordering = {word: i for i, word in enumerate(predefined_list)}

then use that mapping in sorting:

somelist.sort(key=ordering.get)

The alternative is to use .index() on the list to scan through the list and find the index for each word while sorting:

somelist.sort(key=predefined_list.index)

but this is not nearly as efficient as using the ordering dictionary.

Demo:

>>> predefined_list = ['id','name','age','height','weight',]
>>> ordering = {word: i for i, word in enumerate(predefined_list)}
>>> sorted(['height','id'], key=ordering.get)
['id', 'height']
>>> sorted(['name','weight','height'], key=ordering.get)
['name', 'height', 'weight']

The two methods would result in different sorting orders if any of the values in the predefined list were not unique. The .index() method uses the first occurrence of a value as the sort value, the dictionary method would use the last instead. There are ways around that, you can make the dictionary method process the list and indices in reverse for example.

Leave a Comment