Arshanvit
Arshanvit

Reputation: 467

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 :

[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

Upvotes: 0

Views: 51

Answers (2)

Zaid Almoshki
Zaid Almoshki

Reputation: 16

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

Upvotes: 0

AndrejH
AndrejH

Reputation: 2109

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"]))

Upvotes: 3

Related Questions