In Python versions 3.5 and earlier dictionaries cannot store items in an ordered manner like lists or tuples. However, it is possible to create a sorted representation of a dictionary.
Sort dictionary by value
scores = {'Mary': 7, 'Jane': 35, 'Tom': 13}
for key, value in sorted(scores.items(), key=lambda kv: kv[1], reverse=True):
print("%s: %s" % (key, value))
In the above Python 3 code we pass the values from scores.items()
to the sorted()
built-in function and set its sorting key
keyword argument to a lambda function. We've also set the reverse=True
keyword argument so that the scores are sorted in descending order from highest to lowest.
Here are the results:
Jane: 35
Tom: 13
Mary: 7
Note: If you're using Python 2.x you can pass scores.iteritems()
to the sorted()
function.
Sort dictionary by key
If we want to print out the results in alphabetical order, we can sort the dictionary by key like this:
scores = {'Mary': 7, 'Jane': 35, 'Tom': 13}
for key in sorted(scores.keys()):
print("%s: %s" % (key, scores[key]))
Here are the results:
Jane: 34
Mary: 7
Tom: 13
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.