How to Sort a Dictionary in Python

A dictionary is a versatile and widely-used data structure in Python. Often, developers need to sort dictionaries based on keys or values to better process or present the data. In this comprehensive guide, we will cover various methods to sort dictionaries in Python.


1. Understanding Dictionaries in Python

Before diving into sorting, let’s briefly review the dictionary data structure in Python:

Dictionary Definition: A dictionary is an unordered collection of key-value pairs, where each key is unique.

Dictionary Syntax: Dictionaries are defined using curly braces `{}` with key-value pairs separated by colons and elements separated by commas.

example_dict = {"key1": "value1", "key2": "value2", "key3": "value3"}

2. Sorting Dictionaries by Keys

To sort a dictionary by its keys, you can use the `sorted()` function:

sorted_dict = dict(sorted(example_dict.items()))

The `items()` method returns a view object displaying a list of the dictionary’s key-value tuple pairs, which can be sorted using the `sorted()` function.

3. Sorting Dictionaries by Values

If you need to sort a dictionary by its values, you can use the `sorted()` function with a `key` argument:

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

The `key` argument specifies a function that returns a value used for sorting. In this case, we use a lambda function to return the value of each key-value tuple.


4. Sorting in Descending Order

To sort a dictionary in descending order, you can set the `reverse` argument of the `sorted()` function to `True`:

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

5. Sorting with Custom Criteria

You can also sort a dictionary based on custom criteria by modifying the `key` argument within the `sorted()` function. For example, to sort a dictionary based on the length of the values:

sorted_dict = dict(sorted(example_dict.items(), key=lambda item: len(item[1])))

6. Using OrderedDict for Sorted Dictionaries

Python 3.7 introduced the insertion order preservation feature for dictionaries, making the use of `OrderedDict` unnecessary in most cases. However, if you need to work with an older version of Python, you can use the `OrderedDict` class from the `collections` module to maintain the sorted order:

from collections import OrderedDict
sorted_dict = OrderedDict(sorted(example_dict.items()))

7. Sorting Nested Dictionaries

Sorting nested dictionaries requires a custom function that can handle the nested structure. Here’s an example of how to sort a nested dictionary based on its keys:

def sort_nested_dict(d):
return {k: (sort_nested_dict(v) if isinstance(v, dict) else v) for k, v in sorted(d.items())}
sorted_dict = sort_nested_dict(example_dict)


This recursive function sorts the nested dictionaries based on their keys.


8. Conclusion

In this article, we explored various methods to sort dictionaries in Python by keys or values, in ascending or descending order, and using custom criteria. We also covered sorting nested dictionaries and using the `OrderedDict` class for older Python versions.


9. FAQ

Q1: Can I sort a dictionary in-place?

No, dictionaries are unordered collections in Python, so they cannot be sorted in-place. You must create a new dictionary or use the `OrderedDict` class to maintain a sorted order.


Q2: How can I sort a dictionary with multiple criteria?

To sort a dictionary based on multiple criteria, you can modify the `key` argument within the `sorted()` function. For example, to sort a dictionary first by the length of the values and then by the values themselves:

sorted_dict = dict(sorted(example_dict.items(), key=lambda item: (len(item[1]), item[1])))


Q3: Can I sort a dictionary by keys and values simultaneously?

No, a dictionary cannot be sorted by keys and values simultaneously, as the sorting criteria must be unique to establish a definite order. However, you can sort the dictionary based on a combination of keys and values by modifying the `key` argument within the `sorted()` function.


Q4: Can I sort a dictionary based on the order of another list or dictionary?

Yes, you can sort a dictionary based on the order of another list or dictionary. First, create a reference list or dictionary containing the desired order, and then use the `key` argument within the `sorted()` function to sort the dictionary according to the reference:

reference_list = ['key3', 'key1', 'key2']
sorted_dict = dict(sorted(example_dict.items(), key=lambda item: reference_list.index(item[0])))


Q5: How can I sort a dictionary by its keys or values while maintaining the original dictionary?

To sort a dictionary without modifying the original dictionary, create a new dictionary or use a list comprehension to create a list of key-value pairs in the desired order:

# Sort by keys
sorted_dict = dict(sorted(example_dict.items()))
# Or create a sorted list of key-value pairs
sorted_list = sorted(example_dict.items(), key=lambda item: item[1])