[英]Sort a list based on dictionary values in python?
Say I have a dictionary and then I have a list that contains the dictionary's keys.假设我有一本字典,然后我有一个包含字典键的列表。 Is there a way to sort the list based off of the dictionaries values?
有没有办法根据字典值对列表进行排序?
I have been trying this:我一直在尝试这个:
trial_dict = {'*':4, '-':2, '+':3, '/':5}
trial_list = ['-','-','+','/','+','-','*']
I went to use:我去使用:
sorted(trial_list, key=trial_dict.values())
And got:并得到:
TypeError: 'list' object is not callable
Then I went to go create a function that could be called with trial_dict.get()
:然后我去创建一个可以用
trial_dict.get()
调用的函数:
def sort_help(x):
if isinstance(x, dict):
for i in x:
return x[i]
sorted(trial_list, key=trial_dict.get(sort_help(trial_dict)))
I don't think the sort_help
function is having any affect on the sort though.我不认为
sort_help
函数对排序有任何影响。 I'm not sure if using trial_dict.get()
is the correct way to go about this either.我不确定使用
trial_dict.get()
是否是解决此问题的正确方法。
Yes dict.get is the correct (or at least, the simplest) way:是的dict.get是正确的(或者至少是最简单的)方法:
sorted(trial_list, key=trial_dict.get)
As Mark Amery commented, the equivalent explicit lambda:正如 Mark Amery 所评论的,等效的显式 lambda:
sorted(trial_list, key=lambda x: trial_dict[x])
might be better, for at least two reasons:可能会更好,至少有两个原因:
The key argument in the sorted
builtin function (or the sort
method of lists) has to be a function that maps members of the list you're sorting to the values you want to sort by. sorted
内置函数(或列表的sort
方法)中的 key 参数必须是一个函数,它将您正在排序的列表成员映射到您想要排序的值。 So you want this:所以你想要这个:
sorted(trial_list, key=lambda x: trial_dict[x])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.