21

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.

2 Answers 2

21

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).
Sign up to request clarification or add additional context in comments.

6 Comments

Oi, stop jumping in on the questions I'm answering and giving cleverer answers! :) More seriously: there is one difference in behavior between thg's answer and mine. Mine will raise an exception if trial_values contains a value that is not a key of trial_dict, whereas thg's will silently sort that value to the front. Either may be appropriate depending upon context.
@thg435 I should have double checked the docs, I was clearly misunderstanding .get.
@MarkAmery: seriously, yes, the lambda gives you more control and in most cases this is what should be used.
:) Also serious: which of our approaches do you think is stylistically better here? I like the lambda for style reasons even in this case because it means you get to see the expression being sorted on (that is, trial_dict[x]) without doing any further thought; with your answer, I need to visualize the function being called to see that we're sorting on trial_dict.get(x), which requires an extra cognitive step. So I reckon I prefer my approach to yours. Whatcha think?
|
8

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 Comment

I should be keeping lambda in mind for a smaller function like this. I'm marking thg435 as answered but, this was real helpful to, I'll have to think to use the lambda for future use, thanks! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.