Sort Dictionaries by Key, or Value, in Python - Asc, Desc


Introduction

In Python, dictionaries are one of the frequently used data structures, which consist of key-value pairs. The keys in a dictionary are unique, and the values can be of any type.

A Dictionary, a collection of key-value pairs, is not sorted and can change order whenever modified.

Sorting a dictionary based on its keys or values becomes imperative in specific scenarios and can be beneficial for various reasons -

  • We can present the data in a specific order, search or filter, and compare data. Thus, sorting helps in understanding and analyzing data better.
  • Sorting a dictionary simplifies data management, especially for a specific key or value
  • Sorting makes data resemblance fast and efficient, such as encountering the highest or lowest value associated with a key.

Python includes a built-in function, the sorted() function, that we can utilize for efficiently sorting dictionaries by keys or values(in Ascending or Descending manner).

This article aims to explain how to sort dictionaries in Python using the sorted() function, whether by key or value.

sorted() function in Python

To sort a list or dictionary by its keys or values in Python, we can use the built-in sorted() function.

Syntax of sorted() function in Python -

sorted(listOrDict, key=keyFunction, reverse=booleanValue)

Input Parameters -

  • listOrDict: We can pass a list or a dictionary. It's a required parameter.
  • keyFunction: This function acts as a key for the sort comparison. It's an optional parameter.
  • booleanValue: By default, it's false, but if set to True, the sorted list will be reversed (or in Descending order). It's an optional parameter.

Output -

The sorted() function returns a sorted list. It does not change the original list or dictionary passed to it as input.

Sort Dictionary by Key - Python

The sorted() function produces a sorted list of keys from the dictionary.

Using this sorted list of keys, we can access the respective values from the original dictionary using a loop.

Let's understand sorting better with examples.

Example 1: Sorting dictionary by key (Ascending)

Below is the code that demonstrates how to sort a dictionary by its keys in ascending order using the built-in sorted() function in Python:

unsorted_dict = {'c': 20, 'a': 30, 'b': 10}  # Unsorted dictionary

sorted_keys_list = sorted(unsorted_dict)  # Sorted list of keys in Asc order
print(sorted_keys_list)

sorted_dict_by_keys = {key: unsorted_dict[key] for key in sorted_keys_list}
print(sorted_dict_by_keys)  # Print sorted dictionary by keys in Asc order

The Output will be -

['a', 'b', 'c']
{'a': 30, 'b': 10, 'c': 20}

Hence, the dictionary has been sorted based on its keys in ascending alphabetical order.

Explanation:

In the above code example,

  • First, we create an unsorted dictionary called unsorted_dict
  • Next, we use the sorted() function to sort the dictionary's keys ascendingly and store them in a new list named sorted_keys_list.
  • After that, we iterate through the list sorted_keys_list using a for loop and add the corresponding key-value pairs to a new dictionary named sorted_dict_by_keys.
  • And lastly, we print the sorted dictionary.

Example 2: Sorting dictionary by key (Descending)

Below is the code that demonstrates how to sort a dictionary by its keys in descending order using the built-in sorted() function in Python:

unsorted_dict = {"Cadillac": 4, "BMW": 2, "Audi": 3, "Dodge": 1}   # Unsorted dictionary

sorted_keys_list = sorted(unsorted_dict.keys(), reverse=True) # Sort List of keys(Desc order)
print(sorted_keys_list)

sorted_dict_by_keys= {}

for key in sorted_keys_list:
    sorted_dict_by_keys[key]=unsorted_dict[key]

print(sorted_dict_by_keys)  # Print sorted dictionary by keys in Desc order

The Output will be -

['Dodge', 'Cadillac', 'BMW', 'Audi']
{'Dodge': 1, 'Cadillac': 4, 'BMW': 2, 'Audi': 3}

Hence, the dictionary has been sorted based on its keys in descending alphabetical order.

Explanation:

In the above code example,

  • First, we create an unsorted dictionary called unsorted_dict
  • Next, we use the sorted() function with the additional parameter 'reverse=true' to sort the dictionary's keys in descending manner and store them in a new list named sorted_keys_list.
  • After that, we iterate through the list sorted_keys_list using a for loop and add the corresponding key-value pairs to a new dictionary named sorted_dict_by_keys.
  • And lastly, we print the sorted dictionary.

Example 3: Sorting dictionary by key (Asc and Desc - numerical order)

Below is the code that demonstrates how to sort a dictionary by its keys(numerical) using the sorted() function in Python:

# Function to map sorted list with the unsorted dictionary
def sortKeys(keys_list, unsorted_dict):
    sorted_keys = {}
    for key in keys_list:
        sorted_keys[key]=unsorted_dict[key]
    return sorted_keys

# Unsorted dictionary
unsorted_dict = {1: "Kiwi", 4: "Banana", 2: "Orange", 3: "Apple"}

# Sorting based on ascending manner
sorted_keys_list_asc = sorted(unsorted_dict.keys())

# Sorting based on descending manner
sorted_keys_list_desc = sorted(unsorted_dict.keys(), reverse=True)

print(sortKeys(sorted_keys_list_asc, unsorted_dict))
print(sortKeys(sorted_keys_list_desc, unsorted_dict))

The Output will be -

{1: 'Kiwi', 2: 'Orange', 3: 'Apple', 4: 'Banana'}
{4: 'Banana', 3: 'Apple', 2: 'Orange', 1: 'Kiwi'}

Sort Dictionary by Value - Python

We can also use the sorted() function to sort a dictionary by its values. However, in this instance, we must sort the dictionary based on the values instead of the keys.

To accomplish this, we provide a key parameter(keyFunction) to the sorted() function, which specifies the base for sorting the dictionary.

Let's understand better with examples.

Example 1: Sorting dictionary by value (Ascending)

Below is the code that demonstrates how to sort a dictionary by its values in ascending order using the built-in sorted() function in Python:

unsorted_dict = {'c': 20, 'a': 30, 'b': 10}  # Unsorted dictionary

sorted_dict_by_values = {key: value for key, value in sorted(unsorted_dict.items(), key=lambda item: item[1])}

print(sorted_dict_by_values)  # Print sorted dictionary by values in Asc order

The Output will be -

{'b': 10, 'c': 20, 'a': 30}

Hence, the dictionary has been sorted based on its values in ascending order.

Explanation:

In the above code example,

  • We begin by creating an unsorted dictionary named unsorted_dict.
  • Then we pass the unsorted_dict.items() to the sorted() function, along with a key parameter. This key parameter instructs the sorted() function to sort the dictionary based on its values. To do this, we use a lambda function as the key parameter, which returns the value of each key-value pair in the dictionary.
  • Following that, we iterate through the sorted key-value pairs and add them to a new dictionary named sorted_dict_by_values. 
  • Lastly, we print the sorted dictionary.

Example 2: Sorting dictionary by value (Descending)

Below is the code that demonstrates how to sort a dictionary by its values in descending order using the built-in sorted() function in Python:

unsorted_dict = {'c': 20, 'a': 30, 'b': 10}  # Unsorted dictionary

sorted_dict_by_values = {key: value for key, value in sorted(unsorted_dict.items(), key=lambda item: item[1], reverse=True)}

print(sorted_dict_by_values)  # Print sorted dictionary bY values in Desc order

The Output will be -

{'a': 30, 'c': 20, 'b': 10}

Hence, the dictionary has been sorted based on its values in descending order.

Explanation:

In the above code example,

  • We begin by creating an unsorted dictionary named unsorted_dict.
  • Then we pass the unsorted_dict.items() to the sorted() function, along with a key parameter, and 'reverse=True'. This reverse parameter sorts the list in descending order.
  • Following that, we iterate through the sorted key-value pairs and add them to a new dictionary named sorted_dict_by_values. 
  • Lastly, we print the sorted dictionary.

Example 3: Sorting dictionary by value (Asc and Desc - numeric and alphabetic order)

Below is the code that demonstrates how to sort a dictionary by its values(numeric and alphabetic) using the sorted() function in Python:

# Function to sort dictionary
def sortValues(unsorted_dict):
    # Sorting based on ascending manner
    sorted_values_asc = {key: value for key, value in sorted(unsorted_dict.items(), key=lambda item: item[1])}
    # Sorting based on descending manner
    sorted_values_desc = {key: value for key, value in sorted(unsorted_dict.items(), key=lambda item: item[1], reverse=True)}
    return [sorted_values_asc, sorted_values_desc]

# Unsorted dictionaries
unsorted_dict1 = {1: "Kiwi", 4: "Banana", 2: "Orange", 3: "Apple"}
unsorted_dict2 = {'c': 20, 'a': 30, 'b': 10}


print(sortValues(unsorted_dict1)[0]) # dict value sorted in asc
print(sortValues(unsorted_dict1)[1]) # dict value sorted in desc
print('-'*20)
print(sortValues(unsorted_dict2)[0]) # dict value sorted in asc
print(sortValues(unsorted_dict2)[1]) # dict value sorted in desc

The Output will be -

{3: 'Apple', 4: 'Banana', 1: 'Kiwi', 2: 'Orange'}
{2: 'Orange', 1: 'Kiwi', 4: 'Banana', 3: 'Apple'}
--------------------
{'b': 10, 'c': 20, 'a': 30}
{'a': 30, 'c': 20, 'b': 10}

Conclusion

This article has outlined the method to sort Python dictionaries based on key or value. Sorting a dictionary is advantageous in several situations, especially when displaying the dictionary contents in a particular order.

We can sort a dictionary based on its keys using the sorted() function, while sorting based on its values requires using the sorted() function with a key parameter.

Proficiency in sorting dictionaries in Python is an essential skill that can prove beneficial while dealing with vast datasets.

I hope you found this article helpful.

Sort Dictionaries by Key, or Value, in Python - Asc, Desc

Yoy may like to Explore -

OrderedDict class – Python | Explained with Examples

Reverse a string in Python – Different techniques Explained

Parse JSON String and JSON File in Python – Explained

Cheers!

Happy Coding.

About the Author

This article was authored by Aditya Trivedi. Verified by Rawnak.