There are a lot of similar questions on Stack Overflow but not exactly this one.
I need to sort a list of dictionaries based on the values of another list but (unlike all the other questions I found) the second list just gives the order, is not an element of the dictionary.
Let's say I have these lists
a = [{"a": 5}, {"b": 5}, {"j": {}}, {123: "z"}]
b = [8, 4, 4, 3]
Where b
does not contain values of the dictionaries in the list, but gives the order (ascending) to use to sort a
, therefore I want the output to be:
[{123: "z"}, {"b": 5}, {"j": {}}, {"a": 5}]
I tried sorted(zip(b, a)
but this gives an error probably because when it finds a tie it tries to sort on the second list
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In[497], line 1
----> 1 sorted(zip(b, a))
TypeError: '<' not supported between instances of 'dict' and 'dict'
In case of ties it's fine to leave the original order