How to Sort a Dictionary By Value and Key in Python

Last Updated on May 6, 2024 by Roshan Parihar

To sort a Dictionary by value and key in Python, use the sorted() function that is useful for sorting for both purposes.

However, you can also use the pprint() function of Python for sorting of Dictionary by key. Let’s find out the different methods with the examples given below.

How to Sort a Dictionary by Value Using sorted() in Python?

If you want to sort a Dictionary by value in Python, 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 accesses 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 a 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.

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 a 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() for Sorting 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.