Sort Python dictionary by value in Python

In this tutorial, we will learn how to sort a dictionary using values in Python.

How to sort Python dictionary by value in Python?

Now we will learn how to sort Python dictionaries using values.

There are two ways to sort Python dictionaries.

  1. Sorting based on values
  2. Sorting based on keys

1. Sorting based on values

Here we are using a library called Collections. From this, we import the ‘OrderedDict’ function and use it to sort the dictionary.

from collections import OrderedDict
original_dict = {'B': 10, 'D': 9, 'P': 15, 'A': 2}
print(original_dict)
order_value = OrderedDict(sorted(original_dict.items(), key=lambda item: item[1]))
print(order_value)

In the above code, first, we are importing a function named ‘OrderedDict’ from a library called ‘collections’. Then we create a simple dictionary and print it. Then we use the ‘OrderedDict()’ function. Under which we are providing values, using ‘.items()’, in the ‘sorted()’ function. Finally, we are printing it at the end. The ‘item’ variable in lambda function, indicates each key-value tuple. and item[1] tells the sorted() function to consider a second value while sorting.

Output:

{'B': 10, 'D': 9, 'P': 15, 'A': 2}
OrderedDict([('A', 2), ('D', 9), ('B', 10), ('P', 15)])

 Note: Another approach to sort a dictionary using values is to code it using our logic as below:

original_dict = { 'Technology': 2, 'Private': 3,'CodeSpeedy': 1,'Limited':4}
print('Original_keys is :',original_dict)
sorted_dict = {k: v for k, v in sorted(original_data.items(), key=lambda item: item[1])}
print(sorted_dict)

In the above code, we are creating a ‘sorted_dict’ dictionary without using the ‘OrderDict()’ function from collections. Here we are first sorting tuples of key-value pairs based on values and then again we are creating a dictionary of those sorted tuples using the ‘for’ and  ‘in’ clauses. You can understand logic by printing the output of each subsection in the code.

Output:

Original_keys is : {'Technology': 2, 'Private': 3, 'CodeSpeedy': 1, 'Limited': 4}
{'CodeSpeedy': 1, 'Technology': 2, 'Private': 3, 'Limited': 4}

Leave a Reply

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