Sorting Python Dictionaries by Key or Value – Full Guide

1. Introduction

Python is beloved by many developers for its simple and flexible syntax. In particular, the “dictionary (dict)” is a convenient data structure that manages key‑value pairs, streamlining data organization and access. However, while writing programs, the need to “sort a dictionary in a specific order” frequently arises. For example, when you want to sort a student grade sheet or a product price list, you need to arrange the data based on the order of keys or values. In such situations, Python’s “dictionary sorting” feature comes in handy. In this article, we explain concrete methods for sorting Python dictionaries by or values. The explanation is thorough, covering basics to advanced examples, so that beginners through intermediate users can understand—please read through to the end.

2. How to Sort Dictionaries

To sort dictionaries in Python, you mainly use the sorted() function. Here, we will walk through how to sort by keys and values.

2.1 How to Sort a Dictionary by Keys

Use the following code to sort a dictionary by its keys.
sample_dict = {'apple': 3, 'banana': 1, 'cherry': 2}
sorted_by_key = dict(sorted(sample_dict.items(), key=lambda x: x[0]))
print(sorted_by_key)
Result:
{'apple': 3, 'banana': 1, 'cherry': 2}

Code Explanation:

  1. sample_dict.items() retrieves the dictionary as tuples of keys and values.
  2. The sorted() function sorts the items based on the key (x[0]).
  3. Finally, dict() reconstructs it into a new dictionary.
Since this method sorts alphabetically, it is useful when you want to control the order of keys.

2.2 How to Sort a Dictionary by Values

Use the following code to sort based on values.
sample_dict = {'apple': 3, 'banana': 1, 'ch 2}
sorted_by_value = dict(sorted(sample_dict.items(), key=lambda x: x[1]))
print(sorted_by_value)
Result:
{'banana': 1, 'cherry': 2, 'apple': 3}

Code Explanation:

  1. The key=lambda x: x[1] based on the value.
  2. Since it orders from smallest to largest, it is suitable for ranking displays or numeric comparisons.

2.3 Sorting Using the operator Module

To sort more efficiently, you can use Python’s operator module.
from operator import itemgetter

sample_dict = {'apple': 3, 'banana': 1, 'cherry': 2}
sorted_by_value = dict(sorted(sample_dict.items(), key=itemgetter(1)))
print(sorted_by_value)
Result:
{'banana': 1, 'cherry': 2, 'apple': 3}

Code Explanation:

  1. itemgetter(1) retrieves the element at index 1 (the value).
  2. It offers slightly better performance than a lambda function, making it suitable for large datasets.
___HOLDER_1___
RUNTEQ(ランテック)|超実戦型エンジニア育成スクール

3. Reconstructing Sorted Results

Sorting a dictionary typically returns a list of tuples. This explains how to convert it back into a dictionary format.

3.1 Creating a Sorted Dictionary

sorted_items = [('banana', 1), ('cherry', 2), ('apple', 3)]
reconstructed_dict = dict(sorted_items)
print(reconstructed_dict)
Result:
{'banana': 1, 'cherry': 2, 'apple': 3}
Thus, by passing the list of tuples to the dict() function, you can easily revert to a dictionary format.

3.2 Using OrderedDict

From Python 3.7 onward, regular dictionaries preserve order, but if you want to manage order more explicitly, use OrderedDict.
from collections import OrderedDict

sample_dict = {'apple': 3, 'banana': 1, 'cherry': 2}
sorted_by_value = OrderedDict(sorted(sample_dict.items(), key=lambda x: x[1]))
print(sorted_by_value)
Result:
OrderedDict([('banana', 1), ('cherry', 2), ('apple', 3)])
This method is especially useful when dealing with data where order matters.

4. Advanced Examples

In this section, we present advanced examples of sorting dictionaries in Python. In particular, we provide detailed explanations on how to sort a list of dictionaries and how to sort with multiple criteria.

4.1 Sorting a List of Dictionaries by a Specific Key

In Python, you can sort a list of dictionaries by a specific key. This feature is extremely useful when organizing database query results or JSON data. Example 1: Sort student data by age
students = [
    {'name': 'Alice', 'age': 25},
    {'name': 'Bob', 'age': 22},
    {'name': 'Charlie', 'age': 23}
]

sorted_students = sorted(students, key=lambda x: x['age'])
print(sorted_students)
Result:
[{'name': 'Bob', 'age': 22}, {'name': 'Charlie', 'age': 23}, {'name': 'Alice', 'age': 25}]

Code Explanation:

  1. The key=lambda x: x['age'] sorts based on the age key in each dictionary.
  2. Since sorted() returns a new list, the original data remains unchanged.

4.2 Sorting by Multiple Keys

When sorting based on multiple conditions, you can achieve this by using a tuple as the key. Example 2: Sort by both name and age
students = [
    {'name': 'Alice', 'age': 25},
    {'name': 'Bob', 'age': 22},
    {'name': 'Charlie', 'age': 23},
    {'name': 'Alice', 'age': 20}
]

sorted_students = sorted(students, key=lambda x: (x['name'], x['age']))
print(sorted_students)
Result:
[{'name': 'Alice', 'age': 20}, {'name': 'Alice', 'age': 25}, {'name': 'Bob', 'age': 22}, {'name': 'Charlie', 'age': 23}]

Code Explanation:

  1. In key=lambda x: (x['name'], x['age']), it first sorts by name, then by age.
  2. Using a tuple format allows you to easily set priority.

4.3 Specifying Ascending or Descending Order

In Python, you can perform descending sorts by adding reverse=True to the sorted() function. Example 3: Sort ages in descending order
students = [
    {'name': 'Alice', 'age': 25},
    {'name': 'Bob', 'age': 22},
    {'name': 'Charlie', 'age': 23}
]

sorted_students = sorted(students, key=lambda x: x['age'], reverse=True)
print(sorted_students)
Result:
[{'name': 'Alice', 'age': 25}, {'name': 'Charlie', 'age': 23}, {'name': 'Bob', 'age': 22}]

4.4 Sorting Nested Dictionaries

Sorting is also possible when dictionaries contain other dictionaries. Example 4: Sort nested data by points
data = {
    'team1': {'points': 50, 'rank': 2},
    'team2': {'points': 40, 'rank': 3},
    'team3': {'points': 60, 'rank': 1}
}

sorted_data = dict(sorted(data.items(), key=lambda x: x[1]['points']))
print(sorted_data)
Result:
{'team2': {'points': 40, 'rank': 3}, 'team1': {'points': 50, 'rank': 2}, 'team3': {'points': 60, 'rank': 1}}

Code Explanation:

  1. The x[1]['points'] sorts based on the points value within each dictionary.
  2. Even with nested data structures, you can easily sort by simply specifying the required key.

5. Considerations and Best Practices

When sorting dictionaries, please keep the following points in mind.

5.1 Performance with Large Datasets

Sorting dictionaries involves list operations, so processing speed can become an issue with large datasets. Solutions:
  • Use operator.itemgetter to optimize performance.
  • Cache the sorted results to avoid repeatedly processing the same data.

5.2 Differences by Python Version

From Python 3.7 onward, regular dictionaries preserve insertion order, but earlier versions do not guarantee order. Workaround:
  • In older versions, use OrderedDict to manage order.

6. Summary

In this article, we explained various ways to sort Python dictionaries (dict). We covered a wide range from basic sorting by keys or values to advanced sorting of lists and nested dictionaries, as well as sorting with multiple criteria.

Key Takeaways:

  1. Basic sorting methods:
  • Sort by key or value using the sorted() function.
  • You can process efficiently by leveraging lambda functions and operator.itemgetter.
  1. Advanced examples:
  • Sort a list of dictionaries by specific keys or multiple criteria.
  • Nested dictionaries can also be sorted based on a specific key.
  1. Cautions:
  • Consider performance when dealing with large datasets.
  • Be aware of version-dependent behavior and use OrderedDict when necessary.
Sorting Python dictionaries is an essential skill for data organization and analysis. Use the information in this article as a reference and apply it in your own programs.

7. FAQ

Q1: Can a dictionary be sorted directly?

A1: Python dictionaries preserve order, but they cannot be sorted directly. Use the sorted() function to reorder based on keys or values and create a new dictionary.

Q2: What is the difference between OrderedDict and a regular dictionary?

A2: Starting with Python 3.7, regular dictionaries also preserve insertion order, but OrderedDict offers additional features such as reordering and moving entries. Especially in versions prior to Python 3.6, OrderedDict is required when you need to maintain order.

Q3: How should you sort a dictionary when its keys or values are complex data types?

A3: You can handle this by specifying a custom sort key. For example, if you want to sort based on string length or date-time format, you can provide a lambda function to the key argument. Example:
data = {'a': [1, 2], 'b': [3], 'c': [1, 2, 3]}
sorted_data = dict(sorted(data.items(), key=lambda x: len(x[1])))
print(sorted_data)
Result:
{'b': [3], 'a': [1, 2], 'c': [1, 2, 3]}

Q4: How do you reverse the sort order?

A4: You can easily sort in reverse order by adding reverse=True to the sorted() function. Example:
data = {'apple': 3, 'banana': 1, 'cherry': 2}
sorted_data = dict(sorted(data.items(), key=lambda x: x[1], reverse=True))
print(sorted_data)
Result:
{'apple': 3, 'cherry': 2, 'banana': 1}

Q5: How can you revert a sorted result back to the original?

A5: Since dictionaries do not have an inherent order, if you need to preserve the original data order you must manage it using indices or a list. Alternatively, you can use OrderedDict to maintain order. Example:
from collections import OrderedDict

data = {'apple': 3, 'banana': 1, 'cherry': 2}
ordered_data = OrderedDict(data)
print(ordered_data)
侍エンジニア塾