簡體   English   中英

根據 python 中另一個列表中存在的值對 dict 列表進行排序

[英]Sort list of dict based on value present in another list in python

我有以下字典列表:

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

我想根據關鍵字列表對 dict 列表進行排序,然后以有序格式獲取值列表:

[512.06, 1578.0, 15.24]

我正在嘗試遵循代碼但不起作用(將 list_of_sorted_dict 設置為None )。

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

請幫助

您的方法是正確的,但是list.sort()是一種就地排序方法,這意味着它對list_of_dict進行排序並返回None 如果您想要一個單獨的排序變量,您可以執行以下操作。

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

你可以簡單地使用兩個 fors 來實現

    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)

結果:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM