Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

 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]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading