Sorting a list based on dictionary values ​​in python?

Say I have a dictionary, and then I have a list containing the keys of the dictionary. Is there a way to sort a list based on dictionary values?

I tried this:

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

I went to use:

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

And received:

 TypeError: 'list' object is not callable 

Then I went to create a function that can be called using 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 do not think the sort_help function has any effect on sorting. I'm not sure that using trial_dict.get() is the right way to get around this.

+8
python sorting dictionary list
source share
2 answers

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

 sorted(trial_list, key=trial_dict.get) 

As Mark Emery remarked, the equivalent explicit lambda is:

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

could be better for at least two reasons:

  • expression of the form is visible and immediately edited
  • it does not suppress errors (when the list contains what is missing from the dict).
+8
source share

The key argument to the sorted inline function (or the sort list method) should be a function that maps the elements of the list you are sorting to the values ​​you want to sort. So you want:

 sorted(trial_list, key=lambda x: trial_dict[x]) 
+5
source share

All Articles