0

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

Marco
  • 1,454
  • 1
  • 16
  • 30
  • How does `[8,4,4,3]` correspond to that desired output? – Joe Feb 08 '23 at 12:39
  • It seems like you want to sort one list based on the order of another list, and your question actually has nothing to do with dictionaries, correct? – Joe Feb 08 '23 at 12:40
  • 2
    @Joe It does in the sense that with for example strings instead of dict's it wouldn't crash. – Kelly Bundy Feb 08 '23 at 12:41
  • @Joe But if they remove "of dicts" from their Google search, they'll probably get the linked original as the first result (it is for me, even in an anonymous window). – Kelly Bundy Feb 08 '23 at 13:28

1 Answers1

2

You can sort the second list, and then sort the first list based on the result

sort_b_indexes = sorted(range(len(b)),key=lambda x:b[x])
a = [a[i] for i in sort_b_indexes]
sagi
  • 40,026
  • 6
  • 59
  • 84