148

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?

George
  • 15,241
  • 22
  • 66
  • 83

4 Answers4

358

I like this one:

sorted(d, key=d.get)
dF.
  • 74,139
  • 30
  • 130
  • 136
  • 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. – travc Jan 30 '13 at 08:51
107
>>> mydict = {'a':1,'b':3,'c':2}
>>> sorted(mydict, key=lambda key: mydict[key])
['a', 'c', 'b']
dbr
  • 165,801
  • 69
  • 278
  • 343
Markus Jarderot
  • 86,735
  • 21
  • 136
  • 138
17
my_list = sorted(dict.items(), key=lambda x: x[1])
Amelio Vazquez-Reina
  • 91,494
  • 132
  • 359
  • 564
Jonas Kölker
  • 7,680
  • 3
  • 44
  • 51
  • 1
    @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. https://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`. – Jonas Kölker Jun 29 '14 at 14:29
4
[v[0] for v in sorted(foo.items(), key=lambda(k,v): (v,k))]
Can Berk Güder
  • 109,922
  • 25
  • 130
  • 137