Stupid Python tricks, #3296: sorting a dictionary by its values

Suppose you have a dictionary mydict, with key:value pairs

mydict = {'a':5, 'b':2, 'c':1, 'd':6}

You want to sort the keys by the values,  maintaining the keys first in a list of tuples, so that the final list will be:

[('c',1), ('b',2), ('a',5), ('d',6)]

aaaand, the stupid Python trick involves a nested list comprehension:

sorted_list = [(k,v) for v,k in sorted(
                 [(v,k) for k,v in mydict.items()]
                 )
              ]

To get a reverse sorted list:

[('d',6), ('a',5),('b',2),('c',1)]
[(k,v) for v,k in sorted(
   [(v,k) for k,v in mydict.items()],reverse=True
   )
]
Crikey. That's a stupid python if I ever held one!

Crikey. That’s a stupid python if I ever held one!

Share and Enjoy:
  • Fark
  • Digg
  • Technorati
  • del.icio.us
  • StumbleUpon
  • Facebook
  • Reddit
  • Twitter
  • FriendFeed
  • PDF
  • email
  • Print
  • Google Bookmarks

3 Responses to “Stupid Python tricks, #3296: sorting a dictionary by its values”

  1. Petko says:

    This may be a better way to do it:

    sorted(mydict.items(), key = lambda (k,v): v)

  2. Iddo says:

    You are right. It is better. But it is not stupid.

  3. brentp says:

    import operator

    mydict = {‘a':5, ‘b':2, ‘c':1, ‘d':6}

    print sorted(mydict.iteritems(), key=operator.itemgetter(1))