Jvn
Jvn

Reputation: 495

python: How do I sort a list of dictionaries by the order of the values in the other list?

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"}, 
]

Upvotes: 0

Views: 50

Answers (1)

gog
gog

Reputation: 11347

 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]

Upvotes: 3

Related Questions