Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort a list based on dictionary values in python?

Tags:

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.

like image 612
tijko Avatar asked Oct 20 '12 09:10

tijko


People also ask

Can you use sort on a dictionary python?

Introduction. We can sort lists, tuples, strings, and other iterable objects in python since they are all ordered objects. Well, as of python 3.7, dictionaries remember the order of items inserted as well. Thus we are also able to sort dictionaries using python's built-in sorted() function.

How do you sort multiple values in a dictionary python?

Sort Dictionary Using the operator Module and itemgetter() This function returns the key-value pairs of a dictionary as a list of tuples. We can sort the list of tuples by using the itemgetter() function to pull the second value of the tuple i.e. the value of the keys in the dictionary.

Can we sort dictionary values?

It is not possible to sort a dictionary, only to get a representation of a dictionary that is sorted. Dictionaries are inherently orderless, but other types, such as lists and tuples, are not. So you need an ordered data type to represent sorted values, which will be a list—probably a list of tuples.


2 Answers

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).
like image 189
georg Avatar answered Sep 19 '22 15:09

georg


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])
like image 22
Mark Amery Avatar answered Sep 22 '22 15:09

Mark Amery