sort dictionary by values in python

How to Sort Dictionary By Value in Python

Dictionary is a powerful data type in Python that allows you to store diverse data as key-value pairs. By default, python dictionary is sorted in the order of item insertion. Sometimes you may need to sort dictionary by value. In this article, we will look at the different ways to sort dictionary by value in Python.

How to Sort Dictionary By Value in Python

Here are the different ways to sort a Python dictionary by value. Please note, we will not be able to sort the original dictionary but only create a separate dictionary with sorted items. This is because python preserves insertion order in dictionaries.

1. Sort Dictionary using For Loop

In this case, we basically sort the values first using sorted() function, and then loop through the sorted values to get the corresponding keys for each value. Then we add these key-value pairs in the new sorted dictionary.

Here is an example.

>>> a={1:10,3:30,2:20}
>>> a_sort=sorted(a.values())
>>> a_sort
[10, 20, 30]
>>> for i in a_sort:
...     for j in a.keys():
...             if a[j]==i:
...                     b[j]=a[j]
...                     break
>>> b
{1: 10, 2: 20, 3: 30}

Also read : How to Empty or Delete Contents of Large File in Linux

2. Sort Using Sorted Function

We can also use sorted() function in another more efficient way to sort dictionary by values. In this case, we get sorted keys first using a second argument key=a.get in sorted function. get method returns the value of key from dictionary.

>>> a={1:10,3:30,2:20}
>>> b={}
>>> sorted_keys=sorted(a,key=a.get)
>>> sorted_keys
[1, 2, 3]
>>> for i in sorted_keys:
...     b[i]=a[i]
>>> b
{1: 10, 2: 20, 3: 30}

Also read : How to Install Flask in Ubuntu

3. Sorting Dictionary Using Lambda Function

Lambda functions are nameless functions in python. Every dictionary has items method that returns the dict key-value pairs as unordered tuples. In this case, we use lambda function to return the second element of each tuple to key argument of sorted function. That is, we basically return the value of each item to the key argument.

>>> a = {1: 10, 3: 30, 2: 20}
>>> sorted_tuples = sorted(a.items(), key=lambda item: item[1])
>>> print(sorted_tuples)
[(1, 10), (2, 20), (3, 30)]
>>> b = {k: v for k, v in sorted_tuples}
>>> b
{1: 10, 2: 20, 3: 30}

There are many more ways to sort a dictionary by values. We have just listed a few simple & fun ones here. Hope you find them useful.

Also read : How to Convert List to String in Python

Leave a Reply

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