Python
Dictionary
Sorting
Programming
Tutorial

How do I sort a dictionary by key?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Sure! Here’s an article on how to sort a dictionary by key.


Sorting dictionaries by key is a common requirement when managing data in Python. As dictionaries in Python prior to version 3.7 were inherently unordered, the task of sorting was especially necessary if a specific order was desired. Starting with Python 3.7, dictionaries maintain the order of insertion; still, sorting serves the purpose of arranging data for human interpretations or algorithmic processing. Below, we will explore methods for sorting dictionaries by keys using both built-in functionalities and custom implementations.

Understanding Dictionaries

A Python dictionary is a collection of key-value pairs. Each key is unique within a dictionary, and each key is associated with a value. Dictionaries are optimized for retrieving the value when the associated key is known, using syntax like dict[key].

Sorting a Dictionary by Key

Built-in Sorted Functions

The simplest way to sort a dictionary by key is to use Python's built-in sorted() function. This method returns a new dictionary that has its keys sorted.

python
1# Example dictionary
2unsorted_dict = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
3
4# Sorting the dictionary by keys
5sorted_dict = dict(sorted(unsorted_dict.items()))
6print(sorted_dict)

In this example, sorted() sorts the items returned by the dict.items() method, which provides a view of the dictionary's key-value pairs as tuples. When no custom sorting logic is specified, sorted() uses the natural ascending order of keys.

Using collections.OrderedDict

collections.OrderedDict is a specialized dictionary variant that remembers the order in which items were inserted. Prior to Python 3.7, this was essential for maintaining order, but as of 3.7, it's primarily useful for explicit control over order operations.

python
1from collections import OrderedDict
2
3# Example dictionary
4unsorted_dict = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
5
6# Creating an OrderedDict sorted by keys
7sorted_dict = OrderedDict(sorted(unsorted_dict.items()))
8print(sorted_dict)

Similar in syntax to the regular dict sorting, OrderedDict inherently retains the insertion order, which results from the sorting operation.

Dictionary Comprehensions

Another approach to sorting involves dictionary comprehensions in conjunction with the sorted() function. This can be a more Pythonic and concise way, particularly when transformations or filtering steps are desired.

python
1# Example dictionary
2unsorted_dict = {'banana': 3, 'apple': 4, 'pear': 1, 'orange': 2}
3
4# Sorting the dictionary by keys using a dictionary comprehension
5sorted_dict = {k: unsorted_dict[k] for k in sorted(unsorted_dict)}
6print(sorted_dict)

In this approach, we iterate through the keys sorted by the sorted() function and construct a new dictionary.

Key Points and Summary

Here's a table summarizing the key methods of sorting a dictionary by key:

MethodDescriptionPython Version
dict() with sorted()Uses the built-in sorted() function to sort dictionary items and reinsert them as a new dictionary.Python 3+
OrderedDict()Utilizes OrderedDict from collections to maintain an ordered dictionary based on sorted keys.Python 3+ (more relevant pre-3.7)
Dictionary ComprehensionEmploys dictionary comprehensions to generate a sorted dictionary in a concise manner.Python 3+

Additional Considerations

  • Complexity: Sorting operations generally have a complexity of O(nlogn)O(n \log n), where n is the number of items. The choice of sorting method should take this into account for large dictionaries.
  • Locale-Aware Sorting: The above methods presume standard alphabetical order. For locale-aware sorting, consider using the locale.strxfrm function in the key parameter of sorted().
  • Custom Sorting: Python's sorted() allows for custom sort keys using the key argument, enabling powerful extensions like length-based sorting or other criteria.

By choosing the suitable method and understanding the intrinsic offerings of Python collections, sorting dictionaries by key becomes a manageable and straightforward task. Whether using built-in functions or leveraging dictionary comprehensions, the flexibility of Python ensures a variety of approaches are at your disposal.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.