Sort Dictionary by Value in Python

In this tutorial, I will show you how to use the built-in sorted function to sort dictionary by value in python so without wasting any time let’s get started.

sorted() Function

Sorted is the builtin function that takes an iterable as an argument and sorts it in the increasing or decreasing order.

Strings are sorted alphabetically, and numbers are sorted numerically.

syntax :

sorted(iterable, key=None, reverse=False)

iterable : The sequence to sort (eg : list, tuple, dict)

key : A Function to execute to decide the order. Default is None.

reverse : Set to False to sort in ascending and True to descending. default is False.

Sort Dictionary By Value In ascending Order

In this code example, we will use the above discussed sorted function to sort a dictionary by value in ascending order.

Here is the algorithm.

  • We first obtain all the list of all the items of the dictionary in (key, value) pairs.
  • Then we sort that list by value.
  • Finally, we convert the sorted list to the dictionary and return it.
# program to sort dictionary by value in python

def sort_by_value(dic):
    # function to sort dictionary by value in python
    items = dic.items() # grab the list of all items in (key,value) pair
    list_ = sorted(items,key = lambda item: item[1]) # sort the items by value
    return dict(list_) # convert the sorted list to dict and return it

d = {1:2,2:1,8:9,5:5}
s = sort_by_value(d)
print(s)

Here is the output of above code.

Output :

output of code example to sort dictionary by value in python.

Sort Dictionary By In Descending Order

In the below code, we will set the reverse option of sorted function to True to sort in descending order.

def sort_by_value(dic):
    # function to sort dictionary by value in python
    items = dic.items()
    list_ = sorted(items,key = lambda item: item[1],reverse = True) # set the reverse to True
    return dict(list_)

d = {1:2,2:1,8:9,5:5}
s = sort_by_value(d)
print(s)

Output :

{8: 9, 5: 5, 1: 2, 2: 1}

Sort Dictionary By Key In Python

Similarly, we can also use the sorted function to sort the dictionary by key. Here is the code.

def sort_by_key(dic):
    # function to sort the dictionary by key
    items = dic.items()
    list_ = sorted(items) # automatically sort by key
    return dict(list_)

d = {1:2,2:1,8:9,5:5}
s = sort_by_key(d)
print(s)

Output :

{1: 2, 2: 1, 5: 5, 8: 9}

That’s wrap for this tutorial.

Also read about how to convert list to dictionary in python

Leave a Reply