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

Time:06-09

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

CodePudding user response:

 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]
  • Related