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

Sort list of dict based on value present in another list in python

I have following list of dict:

list_of_dict = [
{'vectorName': 'draw', 'value': 52.06}, 
{'vectorName': 'c_percentage', 'value': 15.24}, 
{'vectorName': 'o_temprature', 'value': 1578.0}
]

I have another list of keywords:

list_of_keywords = ['draw', 'o_temprature', 'name', 'c_percentage', 'data']

I want to sort the list of dict based on list of keywords and then get list of values in ordered format :

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

[512.06, 1578.0, 15.24]

I am trying following peice of code but not working (getting list_of_sorted_dict as None).

list_of_sorted_dict = list_of_dict.sort(key=lambda x: list_of_keywords.index(x["vectorName"]))

Kindly help

>Solution :

Your approach is correct, but the list.sort() is an in-place sorting method, which means that it sorts list_of_dict and returns None. If you want a separate sorted variable, you can do the following.

list_of_sorted_dict = sorted(list_of_dict, key=lambda x: list_of_keywords.index(x["vectorName"]))
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