How to Sort a Dictionary By Value and Key in Python

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.

Output

{‘Feroz’: 9, ‘Rock’: 12, ‘John’: 23, ‘Sam’: 29, ‘Billy’: 31}

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.

Output

{‘Billy’: 31, ‘Feroz’: 9, ‘John’: 23, ‘Rock’: 12, ‘Sam’: 29}

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.

Output

{‘Billy’: 31, ‘Feroz’: 9, ‘John’: 23, ‘Rock’: 12, ‘Sam’: 29}

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

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.