Sort list of dictionaries based on the order given by another list

Question:

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

Asked By: Marco

||

Answers:

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]
Answered By: sagi

you can convert your dictionary to list of list and add the element of b to each list. Now you can sorth this list by values of b.

a = [{"a": 5}, {"b": 5}, {"j": {}}, {123: "z"}]
b = [8, 4, 4, 3]
r = [i.items() for i in a]
for i in range(len(r)):
    r[i] = list(r[i])
print(r)
for i in range(len(r)):
    r[i].append(b[i])
print(r)
r.sort(key=lambda x:x[1])
print(r)
c = []
for i in r:
    d = {}
    d[i[0][0]] = i[0][1]
    c.append(d)
print(c)
Answered By: Kaushik Vezzu
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.