How to sort dictionary based on values in Python?

Python – Sort Dictionary based on Values

As of Python version 3.7, dictionaries are ordered, and we can sort a dictionary based on values.

To sort a dictionary based on values in Python, you can use built-in function sorted(). Pass the dictionary items dict.items() for the first argument, and a lambda function that returns value from the item, for the named argument key.

sorted() function returns a list of tuples, and to convert this to a dictionary of key-value pairs, we can use dict() function.

Syntax

The syntax to sort the key-value pairs in a dictionary dict1 based on the values is

dict(sorted(dict1.items(), key=lambda item: item[1]))

item[1] returns value from the item (key-value pair).

Example

In the following example, we take a dictionary with some key-value pairs. We will use sorted() and dict() built-in functions to sort the items in dictionary based on values.

Python Program

dict1 = {
    "key1": 56,
    "key2": 10,
    "key3": 12,
    "key4": 7}

sorted_dict = dict(sorted(dict1.items(), key=lambda item: item[1]))
print(sorted_dict)
Run Code Copy

Output

{'key4': 7, 'key2': 10, 'key3': 12, 'key1': 56}

Summary

In this tutorial, we learned how dictionaries can be sorted based on the values using sorted() built-in function, with examples.

Related Tutorials

Code copied to clipboard successfully 👍