0

The list of dictionaries must be reordered in the order of the values contained in the other list, as shown below.(In this case ["site"].)

The other list contains the values of the dictionary.

In the case of just dictionaries, it is easy to reorder them using comprehensions, etc., but I could not think of a way to reorder the dictionary lists.

How is it possible to reorder them in this way?

l = ["c", "b", "a"]
d = [
    {"id": 1, "site": "a"}, 
    {"id": 2, "site": "c"}, 
    {"id": 3, "site": "b"}
]

↓

[
    {"id": 2, "site": "c"}, 
    {"id": 3, "site": "b"}
    {"id": 1, "site": "a"}, 
]
Jvn
  • 425
  • 4
  • 9
  • Does this answer your question? [How do I sort a dictionary by value?](https://stackoverflow.com/questions/613183/how-do-i-sort-a-dictionary-by-value) – Alexander Jun 08 '22 at 11:20
  • @alexpdev -- Although related there are two differences: 1) OP is sorting a list rather than a dictionary, and 2) the sort order is based upon another list. – DarrylG Jun 08 '22 at 11:26
  • @DarrylG This is the page I meant to comment https://stackoverflow.com/questions/14880780/sorting-list-of-dictionaries-using-the-values-from-another-list-of-dictionaries – Alexander Jun 08 '22 at 11:29

1 Answers1

3
 d.sort(key=lambda item: l.index(item['site']))

should do the trick.

If both lists are really big, a temporary map could be more efficient:

m = {item['site']: item for item in d}
d = [m[site] for site in l]
gog
  • 10,367
  • 2
  • 24
  • 38