根据python中的字典值排序列表? [英] Sort a list based on dictionary values in python?

查看:437
本文介绍了根据python中的字典值排序列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有一个字典,然后我有一个包含字典的键的列表。有没有办法根据字典值排序列表?



我一直在尝试:

  trial_dict = {'*':4,' - ':2,'+':3,'/':5} 
trial_list = [' - ' ','+','/','+',' - ','*']



< >我去使用:

  sorted(trial_list,key = trial_dict.values())

并得到:

  TypeError: 'list'对象不可调用

然后我去创建一个可以使用 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) ))

我不认为 sort_help 功能对排序有任何影响。我不知道是否使用 trial_dict.get()是正确的方法。

解决方案

dict.get 是正确(或至少是最简单的)方式:

  sorted(trial_list,key = trial_dict.get)
如Mark Amery所言,相当于明确的lambda:

$ p> sorted(trial_list,key = lambda x:trial_dict [x])

可能会更好,至少有两个原因:


  1. 排序表达式是可见的,可以立即编辑

  2. 它不会抑制错误(当列表包含不在dict中的东西时)。


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():

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.

解决方案

Yes dict.get is the correct (or at least, the simplest) way:

sorted(trial_list, key=trial_dict.get)

As Mark Amery commented, the equivalent explicit 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).

这篇关于根据python中的字典值排序列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆