37

Possible Duplicate:
In Python how do I sort a list of dictionaries by values of the dictionary?
Sorting Python dictionary based on nested dictionary values

I have dictionary of the form as mentioned below:

a_dict = { 'e': (1, 100), 'a': (2, 3) }

I am unable to sort it by the second element of the tuple. The resultant dictionary will appear as below:

a_dict = { 'a': (2, 3), 'e': (1, 100) }
Community
  • 1
  • 1

2 Answers2

28

Dictionaries can't be sorted as such, but you can sort their contents:

sorted(a_dict.items(), key=lambda (k, (v1, v2)): v2)
sorted(a_dict.items(), key=lambda item: item[1][1])    # Python 3

You can put the results into a collections.OrderedDict (since 2.7):

OrderedDict(sorted(a_dict.items(), key=lambda (k, (v1, v2)): v2))
OrderedDict(sorted(a_dict.items(), key=lambda item: item[1][1])    # Python 3
ecatmur
  • 152,476
  • 27
  • 293
  • 366
  • 6
    The argument unpacking done in your lambda will only work in Python 2.x. In Python 3 you'll need to do `key=lambda k, v : v[1]`. – Blckknght Aug 13 '12 at 11:02
1

In your example you are using list of dictionaries. Sorting the dict by key:

mydict = {'carl':40,
          'alan':2,
          'bob':1,
          'danny':3}

for key in sorted(mydict.iterkeys()):
    print "%s: %s" % (key, mydict[key])

alan: 2
bob: 1
carl: 40
danny: 3

If you want to sort a dict by values, please see How do I sort a dictionary by value?

user
  • 1,220
  • 1
  • 12
  • 31
ymn
  • 2,175
  • 2
  • 21
  • 39
  • 1
    What list of dictionaries are you referring to? The code in the question has a dictionary with tuples as values, and no lists at all. – Blckknght Aug 13 '12 at 11:03
  • Of course you're right. I made a stupid mistake. – ymn Aug 13 '12 at 12:54