How to Sort a Dictionary by Key or Value in Python

Learn how to sort Python dictionaries by values or keys. In this tutorial, we'll cover built-in functions like `sorted()` and `dict.items()` to help you sort dictionaries in ascending or descending order and handle edge cases using `OrderedDict`.

Dictionary Sorting is crucial when working with structured data that requires organization for better readability, analysis, or reporting. While Python dictionaries are optimized for fast look-ups and insertions, their default order is not always ideal for specific tasks like ranking, categorization, or structured exports.

What are Python Dictionaries?

A Python dictionary is a versatile data structure that holds information as key-value pairs enabling effective data organization and retrieval. Tasks such as sorting objects, organizing databases, or improving data presentation often require dictionaries to be arranged by their keys or values.

For example, suppose we have a database of books that is stored as a dictionary that pairs the author’s name to the genre. Sorting dictionaries simplifies these tasks, enabling better organization and quicker data access.

We’ll understand it further in this article

Different ways to sort a dictionary in Python

Sorting a dictionary can be done in multiple ways based on the requirements, such as sorting by keys or values. Python provides built-in functions like sorted() and dict.items() to make this task straightforward.

In this tutorial we will explore various methods to sort dictionaries in Python using built-in functions like sorted() and dict.items()and see how these methods can be applied to real-world problems.

How to sort a dictionary by values in Python

Sorting a dictionary by values in Python allows the data to be organized based on the values associated with the keys, making it easier to analyze or rank the data. While dictionaries are unordered by default, sorting them by values helps organize data for tasks like ranking products by sales or students by scores.

The sorted() function creates a new sorted list without altering the original dictionary.

When sorting dictionaries by values, we need to specify the value Python should use for sorting. This is done using the key argument in the sorted() function, which determines the sorting criterion (in this case, the dictionary values).

For instance, consider the task of sorting a dictionary that stores student scores by their values in ascending order:

# Define dictionary
student_scores = {'Aleena': 68, 'Brayne': 79, 'Charlie': 58}
# Sorting the dictionary by values in ascending order
# key=lambda item: item[1] sorts based on the second element (value) of each tuple.
sorted_items = sorted(student_scores.items(), key=lambda item: item[1])
# Convert the sorted list of tuples back into a dictionary to preserve the key-value structure.
sorted_dict = dict(sorted_items)
# Output the sorted dictionary
print(sorted_dict)

Output:

This example demonstrates how to arrange the dictionary from the lowest score to the highest:

{'Charlie': 58, 'Aleena': 68, 'Brayne': 79}

How to sort a dictionary by values in Ascending Order

Dictionaries can be sorted by their values using Python’s built-in sorted() function, the syntax of which is the following:

sorted(dictionary.items(), key=lambda item: item[1], reverse=False) 
  • iterable: The dictionary.items() method returns a sequence of key-value pairs from the dictionary, which will be sorted.
  • key: The lambda item: item[1] function tells Python to sort the items based on their values (the second element of the tuple, item[1]).
  • reverse: Setting reverse=False ensures the dictionary is sorted in ascending order (from smallest to largest).

This example demonstrates sorting a student_scores dictionary by values in ascending order using sorted() with key=lambda item: item[1] to access each value:

# Define dictionary
student_scores = {'Aleena': 68, 'Brayne': 79, 'Charlie': 58}
# Sorting the dictionary by values in ascending order to rank students by scores, where `sorted()` returns a list of tuples that is converted back into a dictionary.
sorted_dict = dict(sorted(student_scores.items(), key=lambda item: item[1]))
print(sorted_dict)

Output:

{'Charlie': 58, 'Aleena': 68, 'Brayne': 79}

The output displays the student_scores dictionary sorted in ascending order by values, starting with the lowest score (Charlie: 58) and ending with the highest score(Brayne: 79).

How to sort a dictionary by values in descending order

We can sort dictionaries in Python by values in descending order using the sorted() function with the reverse parameter set to True. This method is particularly useful when prioritizing data, such as ranking students by scores or products by sales in descending order.

The syntax for sorting a dictionary by values in descending order is as follows:

 sorted_dict = dict(sorted(dictionary.items(), key=lambda item: item[1], reverse=True)) 

Here, dictionary.items() converts the dictionary into a list of tuples (key-value pairs). The sorted() function is applied to this list of tuples, and the reverse=True parameter ensures that the dictionary is sorted in descending order.

In this example, we start with a dictionary student_scores, which contains student names as keys and their scores as values. The goal is to sort this dictionary by the scores (values) in descending order.

# Define dictionary
student_scores = {'Aleena': 68, 'Brayne': 79, 'Charlie': 58}
# Sorting the dictionary by values in ascending order and converting the list back into dictionary.
sorted_dict = dict(sorted(student_scores.items(), key=lambda item: item[1], reverse=True))
print(sorted_dict)

In the code, the reverse=True parameter is used to sort the dictionary by values in descending order.

Output:

{'Brayne': 79, 'Aleena': 68, 'Charlie': 58}

The code outputs a dictionary sorted by values, which are the students scores, in descending order.

How to sort a dictionary by keys in Python

Sorting dictionaries by keys organizes data systematically, whether in alphabetical, numerical, or custom-defined order. This approach is particularly useful for presenting information in a structured and readable format.

Here’s an example of how to sort a dictionary by its keys in Python:

# Sample dictionary
student_scores = {"Alice": 85, "Bob": 92, "Charlie": 78, "Diana": 88}
# Sorting the dictionary by keys (alphabetical order)
sorted_by_keys = dict(sorted(student_scores.items()))
print(sorted_by_keys)

Output:

{'Alice': 85, 'Bob': 92, 'Charlie': 78, 'Diana': 88}

In this example, the sorted() function arranges the dictionary by keys alphabetically, making the student names more organized and readable

When sorting dictionaries by keys, we can sort them in both ascending and descending order. Let’s start by discussing how to sort dictionary by key in ascending order.

How to sort a dictionary by keys in ascending order

Dictionaries can be sorted in ascending order based on their keys using the sorted() function. By default, the sorting order is ascending unless explicitly set to descending using the reverse parameter.

To understand this better, let’s walk through the syntax of the sorted()function for sorting the dictionary by keys in ascending order:

sorted(dictionary.items(), key=lambda item: item[0], reverse=False) 

Here,

  • dictionary.items(): Converts the dictionary into a list of key-value pairs.
  • reverse=False: Ensures the dictionary is sorted in ascending order by default.

Here’s an example to sort a dictionary by its keys in ascending order.

The student_scores dictionary is sorted in ascending order by its keys (alphabetically), producing a dictionary where the keys are sorted in ascending order.

# Define dictionary
student_scores = {'Brayne': 79, 'Aleena': 68, 'Charlie': 58}
# Sort dictionary by keys in ascending order
sorted_dict = dict(sorted(student_scores.items(), key=lambda item: item[0]))
print(sorted_dict)

Output:

{'Aleena': 68, 'Brayne': 79, 'Charlie': 58}

How to Sort a Dictionary by Key in Descending Order

By using Python’s built-in sorted() function with the key argument, it is possible to arrange the dictionary in the desired order.

To sort a dictionary by key in descending order, we need to set the reverse parameter to True.

Here’s the syntax to sort dictionary by keys in descending order:

sorted(dictionary.items(), key=lambda item: item[0], reverse=True) 

Here,

  • dictionary.items(): Converts the dictionary into a list of key-value pairs.
  • reverse=True: ensures the dictionary is sorted in descending order by the keys.

Here’s an example of sorting a dictionary by keys in descending order. The sorted() function sorts student_scores by keys with reverse=True, and dict() converts the result back into a dictionary.

student_scores = {'Charlie': 85, 'Aleena': 92, 'Brayne': 78}
# Sorting the dictionary by keys in descending order
sorted_dict = dict(sorted(student_scores.items(), key=lambda item: item[0], reverse=True))
print(sorted_dict)

The student_scores dictionary is sorted by its keys (‘Charlie’, ‘Brayne’, and ‘Aleena’) in descending alphabetical order. The result is a new dictionary with keys arranged in descending format.

Output:

{'Charlie': 85, 'Brayne': 78, 'Aleena': 92}

To further enhance the flexibility and stability of sorting, especially in edge cases like empty dictionaries or duplicate values, Python has OrderedDict class from collections module. It ensures that the sorting behavior remains predictable and preserves the insertion order even in cases where the dictionary undergoes frequent changes.

Handling Edge Cases with OrderedDict

In edge cases like empty dictionaries or those with duplicate values, the standard sorted() function may not always behave as expected. In these cases, OrderedDict from the collections module can be used to maintain insertion order and stable sorting.

Benefits of using OrderedDict:

  • Handles duplicate values: Maintains order even when dictionary values are not unique.
  • Stable sorting: Ensures predictable ordering in scenarios where order matters, such as in a task scheduler where tasks must be processed in the exact sequence they were added.
  • Preserves insertion order: Unlike regular dictionaries in earlier Python versions, OrderedDict preserves the order of items as they are inserted.

Let’s see an example where we use OrderedDict:

The OrderedDict ensures that items with duplicate values, like Charlie and Brayne, maintain their original order after sorting:

from collections import OrderedDict
# Define dictionary
student_scores = {'Charlie': 85, 'Aleena': 92, 'Brayne': 85}
# Sorting the dictionary by values and converting to OrderedDict
sorted_dict = OrderedDict(sorted(student_scores.items(), key=lambda item: item[1]))
print(sorted_dict)

The function sorted_dict = OrderedDict(sorted(student_scores.items(), key=lambda item: item[1])) sorts the student_scores dictionary by values in ascending order and stores the result in an OrderedDict, preserving the order of the elements.

Output

OrderedDict([('Charlie', 85), ('Brayne', 85), ('Aleena', 92)])

In this example, OrderedDict maintains the insertion order while sorting by values, even with duplicate values like Charlie and Brayne, maintain their original order after sorting.

Conclusion

In this article, we explored how to sort dictionaries in Python by both keys and values. By using Python’s built-in sorted() function, we learned how to arrange dictionary items in ascending and descending order based on either the keys or the values. These sorting techniques are invaluable for organizing and manipulating your dictionary data efficiently.

To learn more about Python data structures and advanced techniques, explore the Data Structures and Algorithms with Python course on Codecademy.

Author

Codecademy Team

'The Codecademy Team, composed of experienced educators and tech experts, is dedicated to making tech skills accessible to all. We empower learners worldwide with expert-reviewed content that develops and enhances the technical skills needed to advance and succeed in their careers.'

Meet the full team