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. I'm not sure if using trial_dict.get()
is the correct way to go about this either.
我不认为sort_help函数对排序有任何影响。我不确定使用trial_dict.get()是否也是正确的方法。
2 个解决方案
#1
10
Yes dict.get is the correct (or at least, the simplest) way:
get是正确的(或者至少是最简单的)方法:
sorted(trial_list, key=trial_dict.get)
As Mark Amery commented, the equivalent explicit lambda:
正如Mark Amery所说,等价的显式
sorted(trial_list, key=lambda x: trial_dict[x])
might be better, for at least two reasons:
可能会更好,至少有两个原因:
- the sort expression is visible and immediately editable
- 排序表达式是可见的,并且可以立即编辑
- it doesn't suppress errors (when the list contains something that is not in the dict).
- 它不会抑制错误(当列表中包含不在字典中的内容时)。
#2
5
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. So you want this:
排序内建函数(或列表的排序方法)中的关键参数必须是一个函数,该函数将正在排序的列表中的成员映射到要排序的值。所以你想要这样的:
sorted(trial_list, key=lambda x: trial_dict[x])
#1
10
Yes dict.get is the correct (or at least, the simplest) way:
get是正确的(或者至少是最简单的)方法:
sorted(trial_list, key=trial_dict.get)
As Mark Amery commented, the equivalent explicit lambda:
正如Mark Amery所说,等价的显式
sorted(trial_list, key=lambda x: trial_dict[x])
might be better, for at least two reasons:
可能会更好,至少有两个原因:
- the sort expression is visible and immediately editable
- 排序表达式是可见的,并且可以立即编辑
- it doesn't suppress errors (when the list contains something that is not in the dict).
- 它不会抑制错误(当列表中包含不在字典中的内容时)。
#2
5
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. So you want this:
排序内建函数(或列表的排序方法)中的关键参数必须是一个函数,该函数将正在排序的列表中的成员映射到要排序的值。所以你想要这样的:
sorted(trial_list, key=lambda x: trial_dict[x])