目次
- 1 1. Introduction
- 2 2. How to Sort Dictionaries
- 3 3. Reconstructing Sorted Results
- 4 4. Advanced Examples
- 5 5. Considerations and Best Practices
- 6 6. Summary
- 7 7. FAQ
- 7.1 Q1: Can a dictionary be sorted directly?
- 7.2 Q2: What is the difference between OrderedDict and a regular dictionary?
- 7.3 Q3: How should you sort a dictionary when its keys or values are complex data types?
- 7.4 Q4: How do you reverse the sort order?
- 7.5 Q5: How can you revert a sorted result back to the original?
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 thesorted()
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:
sample_dict.items()
retrieves the dictionary as tuples of keys and values.- The
sorted()
function sorts the items based on the key (x[0]
). - Finally,
dict()
reconstructs it into a new dictionary.
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:
- The
key=lambda x: x[1]
based on the value. - 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:
itemgetter(1)
retrieves the element at index 1 (the value).- It offers slightly better performance than a
lambda
function, making it suitable for large datasets.
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 agestudents = [
{'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:
- The
key=lambda x: x['age']
sorts based on theage
key in each dictionary. - 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 agestudents = [
{'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:
- In
key=lambda x: (x['name'], x['age'])
, it first sorts by name, then by age. - 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 addingreverse=True
to the sorted()
function. Example 3: Sort ages in descending orderstudents = [
{'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 pointsdata = {
'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:
- The
x[1]['points']
sorts based on thepoints
value within each dictionary. - 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:
- Basic sorting methods:
- Sort by key or value using the
sorted()
function. - You can process efficiently by leveraging
lambda
functions andoperator.itemgetter
.
- Advanced examples:
- Sort a list of dictionaries by specific keys or multiple criteria.
- Nested dictionaries can also be sorted based on a specific key.
- Cautions:
- Consider performance when dealing with large datasets.
- Be aware of version-dependent behavior and use
OrderedDict
when necessary.
7. FAQ
Q1: Can a dictionary be sorted directly?
A1: Python dictionaries preserve order, but they cannot be sorted directly. Use thesorted()
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 alambda
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 addingreverse=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 useOrderedDict
to maintain order. Example:from collections import OrderedDict
data = {'apple': 3, 'banana': 1, 'cherry': 2}
ordered_data = OrderedDict(data)
print(ordered_data)