[英]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.