I have a list of strings
string_list = ["key_val_1", "key_val_2", "key_val_3", "key_val_4", ...]
and a list with objects
object_list = [object_1, object_2, object_3,...]
Every object object_i has an attribute key.
I want to sort the objects in object_list by the order of string_list.
I could do something like
new_list = []
for key in string_list:
for object in object_list:
if object.key == key:
new_list.append(object)
but there must be a more pythonic way, then this brute force one. 🙂 How would you solve this?
First, create a dictionary mapping object keys to objects:
Next create the sorted list using a list comprehension: