1

I have a dictionary like prob = {('be', 'limited'): 0.004, ('the', 'book'): 0.000432, ......}

for sorting I used

for k, v in sorted(prob, key = lambda x: x[1], reverse = True):
    print k, v 

but it doesn't give the result. ( it just gave me the tuples..) I wanna sort that dictionary according to value.

Bahrom
  • 4,752
  • 32
  • 41
Youngin Na
  • 87
  • 7

1 Answers1

3

You should call sorted with prob.items() otherwise it returns just the keys after sorting takes place.

sorted(prob.items(), key = lambda x: x[1], reverse = True)

You can store it into collection.OrderedDict which remembers the order in which the items were added:

>>> dct = sorted(prob.items(), key=lambda x: x[1], reverse=True)
>>> result = collections.OrderedDict(dct)
Ozgur Vatansever
  • 49,246
  • 17
  • 84
  • 119