How to Sort a Python Dictionary by Keys or Values

1 min read

A dictionary in Python cannot store items in an ordered manner like lists or tuples. However, there are times when you may want to sort a dictionary in some way. For example, let's say you wanted to rank a dictionary of players and their scores.

Sort a dictionary by keys

scores = {

'Peter': 7,

'Jane': 35,

'Mary': 13,

'Tom': 24,

}


for key in sorted(scores.keys()):

print("%s: %s" % (key, scores[key]))

Here are the results:

Jane: 34

Mary: 13

Peter: 7

Tom: 24

The above code prints the players and their scores in ascending alphabetical order of the keys in the dictionary, i.e. the players names.

Sort a dictionary by values

Sorting a dictionary by values is a little more complex. 

scores = {

'Peter': 7,

'Jane': 35,

'Mary': 13,

'Tom': 24,

}


for key, value in sorted(scores.iteritems(), key=lambda (k,v): (v,k), reverse=True):

print("%s: %s" % (key, value))

Here we set key (i.e. to sort by) keyword argument in the sorted() function. In this case we set it to a lambda function, and that lambda function returns a tuple containing the value and the key. In other words, we're telling the sorted() function to sort according to the dictionary value and then by the dictionary key, in case there are instances where there is more than one of the same score. We've also set the reverse keyword argument to True so that the scores or sorted in descending order from highest to lowest.

Here are the results:

Jane: 35

Tom: 24

Mary: 13

Peter: 7

In the above examples the code prints out the values in their respective order but if you want to store these ordered values for later processing in your code you may want to consider adding them to a list instead.


Author picture
Rhett Trickett

Founder at Able. Building a better developer community. Usually coding with Python and JavaScript.

@rhett RhettTrickett rhetttrickett
Python

Join the discussion

Able is a developer community where people build their coding knowledge and careers.

Join with GitHub Join with Twitter