150

I have a dict where each key references an int value. What's the best way to sort the keys into a list depending on the values?

1
  • 8
    Also, this asks about sorting by key, the linked answer is about sorting by value. Commented Jun 12, 2013 at 8:31

4 Answers 4

360

I like this one:

sorted(d, key=d.get)
Sign up to request clarification or add additional context in comments.

1 Comment

Nice, thought it would be nice to have an elegant solution which gives (key,value) pairs sorted by key. ...and doesn't require providing the dict variable name more than once (I tend to have very long descriptive variable names). d.iteritems() still seems the most useful.
107
>>> mydict = {'a':1,'b':3,'c':2}
>>> sorted(mydict, key=lambda key: mydict[key])
['a', 'c', 'b']

Comments

17
my_list = sorted(dict.items(), key=lambda x: x[1])

1 Comment

@user815423426 you edited my post s/list/my_list/ because "list is a keyword in python". Your edit is fine, but list is not a keyword (c.f. docs.python.org/3/reference/lexical_analysis.html#keywords), so my program fragment would (bytecode-)compile and run. It is however a name in the __builtins__ namespace, and it is bad practice to shadow that name—with a locale variable named list—and horrible to override it—with a global variable named list, e.g. list = tuple.
4
[v[0] for v in sorted(foo.items(), key=lambda(k,v): (v,k))]

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.