Home > DeveloperSection > Forums > Sort a Python dictionary by value
Sanjay Sharma
Sanjay Sharma

Total Post:45

Points:315
Posted on    May-13-2015 12:22 AM

 Python Dictionary  Python 
Ratings:


 1 Reply(s)
 480  View(s)
Rate this:

I have a dictionary of values read from two fields in a database: a string field and a numeric field. The string field is unique, so that is the key of the dictionary.

I can sort on the keys, but how can I sort based on the values?



Mayank Tripathi
Mayank Tripathi

Total Post:397

Points:3117
Posted on    May-13-2015 6:37 AM

It is not possible to sort a dict, only to get a representation of a dict that is sorted. Dicts are inherently orderless, but other types, such as lists and tuples, are not. So you need a sorted representation, which will be a list—probably a list of tuples.

For instance,

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(1))
sorted_x will be a list of tuples sorted by the second element in each tuple. dict(sorted_x) == x.

And for those wishing to sort on keys instead of values:

import operator
x = {1: 2, 3: 4, 4: 3, 2: 1, 0: 0}
sorted_x = sorted(x.items(), key=operator.itemgetter(0))

Don't want to miss updates? Please click the below button!

Follow MindStick