Articles

How to Sort a Dictionary by Key or Value in Python

Learn how to sort Python dictionaries by keys or values using built-in functions like `sorted()` and handle edge cases with `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.

Registration form having data in the form of a key-value pair illustrating a Python dictionary

Imagine a registration form that stores user details like name and age, it illustrates the key-value pair in the python dictionary. But why is there a need to solve the data stored in it?

Related Course

Learn Sorting Algorithms with Python

Learn about the usefulness and efficiency of computational sorting by implementing different sorting algorithms yourself.Try it for free

Why sort a dictionary in Python

Sorting a dictionary is useful when there is a need to organize data for better readability, efficient reporting, or accurate analysis. While dictionaries are optimized for quick access, their order is not always meaningful. Some benefits of sorting are listed as follows:

  • Organize data alphabetically or numerically
  • Easily display rankings (e.g., top scores or highest sales)
  • Generate structured reports or exports
  • Improve readability for users and developers
  • Enable consistent and predictable data outputs

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. Let us explore these methods.

How to use sorted() to sort a Python dictionary by values

Python provides the built-in sorted() function to efficiently sort dictionaries. The sorted() function returns a new sorted list derived from the elements of any iterable. When applied to a dictionary’s items, it enables sorting by values in ascending or descending order. The syntax for the sorted() function is:

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

Parameters:

  • iterable: An iterable to be sorted; in this case, dictionary.items() returns key-value pairs.

  • key (optional): A function that defines the sorting criterion. To sort by values, use lambda item: item[1].

  • reverse (optional): If True, the iterable is sorted in descending order. The default is False for ascending order.

Return value:

Returns a list of tuples representing the sorted key-value pairs. To reconstruct a dictionary from this list, the dict() constructor can be used.

Sorting a dictionary by values in ascending order

To sort in ascending order, use sorted() with key=lambda item: item[1]. This sorts the dictionary items by value from lowest to highest.

Example:

student_scores = {'Aleena': 68, 'Brayne': 79, 'Charlie': 58}
sorted_dict = dict(sorted(student_scores.items(), key=lambda item: item[1]))
print(sorted_dict)

The output this code produces will be:

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

The items() method converts the dictionary into a list of tuples. The key parameter directs the sorting based on the second element of each tuple (the value). The result is a new dictionary sorted in ascending order by values.

Sorting a dictionary by values in descending order

For descending order, the reverse parameter is set to True, which arranges values from highest to lowest.

Example:

student_scores = {'Aleena': 68, 'Brayne': 79, 'Charlie': 58}
sorted_dict = dict(sorted(student_scores.items(), key=lambda item: item[1], reverse=True))
print(sorted_dict)

The output of this code will be:

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

The reverse=True argument instructs the sorted() function to sort the values in descending order. The resulting dictionary presents the highest values first.

How to use sorted() to sort a Python dictionary by keys

Sorting a dictionary by keys is essential for presenting data in a structured, alphabetical, or logical order. This is commonly used in scenarios such as alphabetical listings of names, categories, or labeled data in reports. Python’s sorted() function can be applied to a dictionary’s items to sort them based on their keys.

Sorting a dictionary by keys in ascending order

To sort a dictionary by keys in ascending (default) order, use the sorted() function with key=lambda item: item[0]. This directs the function to sort based on the first element of each tuple (the key).

Example:

student_scores = {'Brayne': 79, 'Aleena': 68, 'Charlie': 58}
sorted_dict = dict(sorted(student_scores.items(), key=lambda item: item[0]))
print(sorted_dict)

The output of this code will be:

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

The items() method returns key-value pairs, and key=lambda item: item[0] ensures the sorting is based on the dictionary’s keys. The sorted result is converted back into a dictionary in ascending alphabetical order.

Sorting a dictionary by keys in descending order

To sort a dictionary by keys in descending order, use the same key function as above, but set the reverse parameter to True.

Example:

student_scores = {'Charlie': 85, 'Aleena': 92, 'Brayne': 78}
sorted_dict = dict(sorted(student_scores.items(), key=lambda item: item[0], reverse=True))
print(sorted_dict)

The output generated by this code will look like:

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

Using reverse=True instructs Python to sort the keys in descending order. The final dictionary is structured so the keys appear from Z to A (or highest to lowest if numerically labeled).

But how can sorting remain predictable when dealing with edge cases like duplicate values, empty dictionaries, or frequently updated data? Python offers a stable solution—let’s explore it with OrderedDict.

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.

Example:

The following example demonstrates how OrderedDict maintains the original insertion order of items with duplicate values:

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 output of this code will look like:

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

The student_scores dictionary is sorted by values in ascending order. Since both 'Charlie' and 'Brayne' have the same value (85), OrderedDict preserves their original insertion order. This ensures a stable and predictable result, even when values are duplicated.

Conclusion

In this article, we explored how to sort Python dictionaries by keys—to organize entries alphabetically or numerically—and by values—to rank data based on importance or frequency. Using sorted() and OrderedDict, we saw how sorting enhances the readability and usefulness of dictionary data in real-world applications.

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

Frequently asked questions

1. What is the best way to sort a dictionary in Python?

The best way to sort a dictionary in Python is by using the sorted() function along with dictionary.items() and specifying a sorting key with a lambda function. For example:

sorted(dictionary.items(), key=lambda item: item[1])

This allows sorting by values. To sort by keys, use item[0] instead.

2. What is the time complexity of sorting a dictionary?

The time complexity of sorting a dictionary using sorted() is O(n log n), where n is the number of items in the dictionary. This is because the sorted() function internally uses Timsort, a hybrid sorting algorithm with that complexity.

3. How does the dictionary data structure work?

A Python dictionary is implemented as a hash table, allowing average-case O(1) time complexity for insertions, deletions, and lookups. Keys must be immutable and are hashed to determine their storage index.

4. Are dictionaries automatically sorted?

No, dictionaries are not automatically sorted. However, starting with Python 3.7, dictionaries preserve the insertion order of items, but this should not be confused with sorting by key or value.

5. Does a dictionary maintain order in Python?

Yes, as of Python 3.7 and later, dictionaries maintain the insertion order of items. In earlier versions, this behavior was not guaranteed. To explicitly control order, especially after sorting, use OrderedDict.

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