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.
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.
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.
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.
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:
| Method | Description | Python 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 Comprehension | Employs dictionary comprehensions to generate a sorted dictionary in a concise manner. | Python 3+ |
Additional Considerations
- Complexity: Sorting operations generally have a complexity of , 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.strxfrmfunction in thekeyparameter ofsorted(). - Custom Sorting: Python's
sorted()allows for custom sort keys using thekeyargument, 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
- How do I sort a dictionary by value?
- How do I sort a list of objects based on an attribute of the objects?
- How do I sort a list of objects based on an attribute of the objects?
- How do I sort a Set to a List in Java?
- How do I sort an array of objects in reverse order efficiently?
- How do I sort an NSMutableArray with custom objects in it?
- How do I split a list into equally-sized chunks?
- How do I split a multi-line string into multiple lines?

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 courseTrack 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.