tijko tijko - 8 months ago 19
Python Question

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

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
function is having any affect on the sort though. I'm not sure if using
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).