How do I sort a dictionary by key?

Learn how do i sort a dictionary by key? with practical examples, diagrams, and best practices. Covers python, sorting, dictionary development techniques with visual explanations.

How to Sort a Python Dictionary by Key

Hero image for How do I sort a dictionary by key?

Learn various methods to sort a Python dictionary by its keys, including using sorted(), dictionary comprehensions, and collections.OrderedDict for Python versions prior to 3.7.

Dictionaries in Python are inherently unordered collections of key-value pairs. While Python 3.7+ guarantees insertion order, this doesn't mean they are sorted by key. If you need to process or display dictionary items in a specific order based on their keys, you'll need to sort them explicitly. This article explores common and efficient ways to achieve this, providing practical code examples and explanations.

Understanding Dictionary Order in Python

Before Python 3.7, dictionaries did not preserve insertion order, meaning the order of items could vary. From Python 3.7 onwards, dictionaries maintain insertion order. However, this is distinct from sorting by key. Sorting by key means arranging the key-value pairs based on the alphabetical or numerical order of the keys themselves, not the order in which they were added. When you sort a dictionary, you typically get an ordered sequence of its items, often as a list of tuples, rather than a modified dictionary object directly.

flowchart TD
    A[Original Dictionary] --> B{Sort by Key?}
    B -- Yes --> C[Get Keys]
    C --> D[Sort Keys]
    D --> E[Iterate Sorted Keys]
    E --> F[Access Values]
    F --> G[Construct New Ordered Structure (e.g., List of Tuples, OrderedDict)]
    B -- No --> H[Maintain Insertion Order (Python 3.7+)]

Conceptual flow for sorting a dictionary by key.

Method 1: Using sorted() with dict.items()

The most common and Pythonic way to sort a dictionary by its keys is to use the built-in sorted() function. This function returns a new sorted list from the items in an iterable. When applied to dict.items(), it sorts the key-value pairs (which are represented as tuples) based on the first element of each tuple (the key) by default.

my_dict = {'apple': 3, 'banana': 1, 'cherry': 2, 'date': 4}

# Sort by key using sorted() on dict.items()
sorted_items = sorted(my_dict.items())
print(f"Sorted items (list of tuples): {sorted_items}")

# To reconstruct an OrderedDict (for Python < 3.7 or explicit ordering)
from collections import OrderedDict
sorted_ordered_dict = OrderedDict(sorted_items)
print(f"Sorted OrderedDict: {sorted_ordered_dict}")

# To reconstruct a regular dictionary (Python 3.7+ preserves order)
sorted_dict = dict(sorted_items)
print(f"Sorted regular dictionary (Python 3.7+): {sorted_dict}")

Sorting a dictionary by key using sorted() and reconstructing various dictionary types.

Method 2: Using a Dictionary Comprehension (Python 3.7+)

For Python 3.7 and later, where dictionaries preserve insertion order, you can leverage a dictionary comprehension to create a new dictionary that is sorted by key. This method is often more concise and readable if your goal is to produce a new dictionary directly.

my_dict = {'apple': 3, 'banana': 1, 'cherry': 2, 'date': 4}

# Sort by key using a dictionary comprehension
sorted_dict_comprehension = {key: my_dict[key] for key in sorted(my_dict)}
print(f"Sorted dictionary (comprehension): {sorted_dict_comprehension}")

Sorting a dictionary by key using a dictionary comprehension.

Method 3: Sorting by Key with Custom Logic

Sometimes, you might need to sort keys based on custom criteria, not just their natural order. The sorted() function allows you to specify a key argument, which is a function to be called on each list element prior to making comparisons. This is useful for case-insensitive sorting, sorting by length, or other complex rules.

my_dict = {'Apple': 3, 'banana': 1, 'Cherry': 2, 'date': 4}

# Case-insensitive sort
sorted_case_insensitive = {k: my_dict[k] for k in sorted(my_dict, key=str.lower)}
print(f"Case-insensitive sorted: {sorted_case_insensitive}")

# Sort by key length
sorted_by_length = {k: my_dict[k] for k in sorted(my_dict, key=len)}
print(f"Sorted by key length: {sorted_by_length}")

# Sort by key length, then alphabetically for ties
sorted_by_length_then_alpha = {k: my_dict[k] for k in sorted(my_dict, key=lambda x: (len(x), x.lower()))}
print(f"Sorted by length then alpha: {sorted_by_length_then_alpha}")

Examples of custom sorting logic for dictionary keys.