Last Updated on June 30, 2021 by Roshan Parihar
In this tutorial, learn how to sort a Dictionary by value and key using Python. The short answer is to use the sorted()
function of Python that is useful for sorting for both purposes.
However, you can also use the pprint()
function of Python to sort Dictionary by key. Let’s find out the different methods with the examples given below.
Sort a Dictionary by Value Using sorted() in Python
To sort a Dictionary by value, you have to use the sorted()
function that takes two arguments. The first argument is the Dictionary variable concatenated with items()
function. The second argument is the key=lambda x:x[1]
that access the second element of Dictionary (i.e. value) for sorting.
But, it creates a list-like container in the form of (key, value) tuples. So, you need to convert the tuples into Dictionary using dict()
function. As a result, you will get the output as a sorted Dictionary.
1 2 3 4 5 6 7 8 9 |
#Define Dictionary variable myDict = {"Billy":31, "Rock": 12, "Sam": 29, "John": 23, "Feroz":9} #sort Dictionary by value using sorted() newListing = sorted(myDict.items(), key=lambda x:x[1]) sortmyDict = dict(newListing) #Print result print(sortmyDict) |
Output
The above example shows the sorted Dictionary by values. The values are sorted numerically in ascending order.
How to Sort Dictionary by Key with sorted() Using Python
Similarly, you can also sort the Dictionary by key using the sorted()
in Python. The function takes a single argument as the Dictionary variable concatenated with the items()
function.
As a result, it is converted to sorted (key, value) tuples. After that, you have to use the dict()
to convert the tuple into Dictionary in Python.
1 2 3 4 5 6 7 8 |
#Define Dictionary variable myDict = {"Billy":31, "Rock": 12, "Sam": 29, "John": 23, "Feroz":9} #sort a Dictionary by key using sorted() in Python sortmyDict = dict(sorted(myDict.items())) #Print result print(sortmyDict) |
Output
The output shows the sorted keys in ascending alphabet order.
Using pprint() in Python
In addition to the above methods, you can also use the pprint()
function of Python. The function is simple to use and takes a single argument as the Dictionary variable.
1 2 3 4 5 6 7 |
from pprint import pprint #Define Dictinary variable myDict = {"Billy":31, "Rock": 12, "Sam": 29, "John": 23, "Feroz":9} #Sort Dictionary and print the result using pprint() pprint(myDict) |
Output
It gives the same result as you have got in the previous example. As a result, the elements of the Dictionary are sorted in ascending order alphabetically.
You May Also Like to Read