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

Question:

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 :

[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

Asked By: Arshanvit

||

Answers:

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"]))
Answered By: AndrejH

Since you are asking for the list of values, here is the full answer:

list_of_sorted_dict = [
    l["value"] for l in sorted(list_of_dict, key=lambda x: 
    list_of_keywords.index(x["vectorName"]))
]
Answered By: HeyMan

you can simply use two fors to achieve that

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

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

list_of_sorted_dict = []

for key in list_of_keywords:
    for item in list_of_dict:
        if(item['vectorName'] == key):
            list_of_sorted_dict.append(item)   

print (list_of_sorted_dict)

result :

[{‘vectorName’: ‘draw’, ‘value’: 52.06}, {‘vectorName’: ‘o_temprature’, ‘value’: 1578.0}, {‘vectorName’: ‘c_percentage’, ‘value’: 15.24}]

Answered By: Zaid Almoshki
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.