Youngin Na Youngin Na - 7 months ago 7
Python Question

how can I sort dictionary whose key is tuple and value is int?

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.

Answer

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)
Comments