Wednesday, April 6, 2011

Sorting dictionary keys in python

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?

From stackoverflow
  • >>> mydict = {'a':1,'b':3,'c':2}
    >>> sorted(mydict, key=lambda key: mydict[key])
    ['a', 'c', 'b']
    
    MizardX : thanks, Brian R. Body. :)
    MizardX : Bondy* ... can't spell tody
  • list = sorted(dict.items(), key=lambda x: x[1])
    
  • [v[0] for v in sorted(foo.items(), key=lambda(k,v): (v,k))]
    
  • I like this one:

    sorted(d, key=d.get)
    
    Kiv : This is really the most elegant.
    Richard J. Terrell : Too bad I haven't waited with the accept. +1
  • odict might work for you.

0 comments:

Post a Comment