Sort Dictionary by value in Python

Dictionary in Python is an unordered collection to store data values in key:value pairs. Since Dictionaries are unordered collections, it is not possible to sort the dictionary in Python. Hence some data structures like lists, tuples need to be used to perform sorting.

Python sorted() function to rescue

Python built-in sorted() method can sort types, such as lists tuples and dictionary values. The sorted() function sorts the items of the specified iterable object and creates a new object with the newly sorted values.

Syntax: sorted(iterable, key, reverse)

This method takes three parameters

  1. Object: the iterable object sequence (list, tuple, string) or collection (dictionary, set, frozenset) that you want to sort.
  2. Key(optional): a function that allows you to perform the sort operation
  3. Reverse(optional): specifies if the object needs to be sorted in descending order. If you don’t specify anything, it will sort in ascending order.

Since the object is the only required parameter, Python will sort the object ascending if you don’t pass the key and reverse in the sorted method.

Sort a Dictionary by Value

Let’s take a few examples here to understand how sorted() works in Python.

Example 1: Basic Sorting in Python

In the below example we are sorting the numbers in both ascending and descending order by using sorted() method.

x = [4, 2, 1, 5, 7, 3, 8] 
print ("Sorted List returned :"), 
print (sorted(x)) 
  
print ("\nReverse sort :"), 
print (sorted(x, reverse = True))
  
print ("\nOriginal list not modified :"), 
print (x) 

Output

Sorted List returned : [1, 2, 3, 4, 5, 7, 8]

Reverse sort : [8, 7, 5, 4, 3, 2, 1]

Original list not modified : [4, 2, 1, 5, 7, 3, 8] 

Example 2 : Sorting different Data Types in Python

Now that we have seen basic sorting let’s check how to perform a sort on different data types like list, tuple, set, dictionary, frozen set, etc.

# List
x = ['q', 'w', 'r', 'e', 't', 'y']
print (sorted(x))
  
# Tuple
x = ('q', 'w', 'e', 'r', 't', 'y')
print (sorted(x))
  
# String-sorted based on ASCII translations
x = "python"
print (sorted(x))
  
# Dictionary
x = {'q':1, 'w':2, 'e':3, 'r':4, 't':5, 'y':6}
print (sorted(x))
  
# Set
x = {'q', 'w', 'e', 'r', 't', 'y'}
print (sorted(x))
  
# Frozen Set
x = frozenset(('q', 'w', 'e', 'r', 't', 'y'))
print (sorted(x))


Output

['e', 'q', 'r', 't', 'w', 'y']
['e', 'q', 'r', 't', 'w', 'y']
['h', 'n', 'o', 'p', 't', 'y']
['e', 'q', 'r', 't', 'w', 'y']
['e', 'q', 'r', 't', 'w', 'y']
['e', 'q', 'r', 't', 'w', 'y']

Example 3: Sort a Dictionary by Value in Python Descending

Let’s say you have a dictionary and you want to sort by key-value pairs. We could perform this by using two functions items() and sorted().
The item() function retrieves the values from the dictionary, and the sorted() function with a custom key parameter will sort the dictionary by value.

Below code will sort the dictionary by the values of each entry within the dictionary in descending order using a lambda function.

orders = {
	'Pizza': 33,
	'Burger': 45,
	'Sandwich': 67,
	'Latte': 39,
	'Snickers': 48
}

sort_orders = sorted(orders.items(), key=lambda x: x[1], reverse=True)

for i in sort_orders:
	print(i[0], i[1])

Output

Sandwich 67
Snickers 48
Burger 45
Latte 39
Pizza 33

Example 4: Sort a Dictionary by Value in Python Ascending

Below code will sort the dictionary by the values of each entry within the dictionary in ascending order using a lambda function

orders = {
	'Pizza': 33,
	'Burger': 45,
	'Sandwich': 67,
	'Latte': 39,
	'Snickers': 48
}

sort_orders = sorted(orders.items(), key=lambda x: x[1])

for i in sort_orders:
	print(i[0], i[1])

Output

Pizza 33
Latte 39
Burger 45
Snickers 48
Sandwich 67

Note: With the release of Python version 3.7 and above by default, dictionaries have been modified to maintain insertion order, which means now dictionaries are ordered collection of data values.

Leave a Reply

Your email address will not be published.

Sign Up for Our Newsletters

Get notified of the best deals on our WordPress themes.

You May Also Like
Python String Isprintable()

Python String isprintable()

Table of Contents Hide What are printable characters in Python?isprintable() Syntaxisprintable() Parametersisprintable() Return ValueExample 1: Working of isprintable() method Example 2: How to use isprintable() in real world? The Python…
View Post
Python Divmod()

Python divmod()

Table of Contents Hide divmod() Syntax divmod() Parametersdivmod() Return ValueExample: How divmod() works in Python?Errors And Exceptions  The divmod() in Python is a built-in function that takes two numbers as input…
View Post
Powershell Concatenate String

PowerShell Concatenate String

Table of Contents Hide Introduction to PowerShell Concatenate StringHow to Concatenate Strings and Variables in PowerShell#1. Expanding Strings#2. Substitution or string.Format approach#3 Join Operator Microsft PowerShell scripting is little different from…
View Post