简体   繁体   English

根据python中的字典值对列表进行排序?

[英]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:可能会更好,至少有两个原因:

  1. the sort expression is visible and immediately editable排序表达式可见并可立即编辑
  2. it doesn't suppress errors (when the list contains something that is not in the dict).它不会抑制错误(当列表包含不在字典中的内容时)。

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM