Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to sort a dictionary in Python?
A dictionary is a data structure that consists of key and value pairs. We can sort a dictionary using two criteria −
Sort by key − The dictionary is sorted in ascending order of its keys. The values are not taken care of.
Sort by value − The dictionary is sorted in ascending order of the values.
Sort Dictionary by Key
In this approach, the dictionary is sorted in ascending order of its keys.
Input:
{2:90, 1: 100, 8: 3, 5: 67, 3: 5}
Output:
{1:100, 2:90, 3:5, 5:67, 8:3}
As shown above, we can see the dictionary is sorted according to its keys.
Using Loop with sorted()
dic = {2:90, 1: 100, 8: 3, 5: 67, 3: 5}
dic2 = {}
for i in sorted(dic):
dic2[i] = dic[i]
print(dic2)
{1: 100, 2: 90, 3: 5, 5: 67, 8: 3}
Using Dict Comprehension
A more concise approach using dictionary comprehension ?
dic = {2:90, 1: 100, 8: 3, 5: 67, 3: 5}
sorted_dict = {key: dic[key] for key in sorted(dic)}
print(sorted_dict)
{1: 100, 2: 90, 3: 5, 5: 67, 8: 3}
How It Works
-
sorted(dic)returns all the keys of the dictionary in sorted order as a list: [1, 2, 3, 5, 8] - For each key in sorted order, we add the key and corresponding value to the new dictionary
- The result is a dictionary with all key-value pairs in sorted order of keys
Sort Dictionary by Values
In this approach, the dictionary is sorted in ascending order of values.
Input:
{2:90, 1: 100, 8: 3, 5: 67, 3: 5}
Output:
{8:3, 3:5, 5:67, 2:90, 1:100}
As shown above, we can see the dictionary is sorted according to its values.
Using sorted() with items()
dic = {2:90, 1: 100, 8: 3, 5: 67, 3: 5}
dic2 = dict(sorted(dic.items(), key=lambda x: x[1]))
print(dic2)
{8: 3, 3: 5, 5: 67, 2: 90, 1: 100}
How It Works
- The
items()method returns key-value pairs as tuples: [(2, 90), (1, 100), ...] - The
key=lambda x: x[1]tellssorted()to sort by the second element (value) of each tuple -
dict()converts the sorted list of tuples back into a dictionary
Comparison
| Method | Sorts By | Best For |
|---|---|---|
| Loop with sorted() | Keys | Beginners, step-by-step approach |
| Dict comprehension | Keys | Concise, readable code |
| sorted() with items() | Values | Sorting by values or complex criteria |
Conclusion
Use dictionary comprehension with sorted() for sorting by keys. Use sorted() with items() and a lambda function for sorting by values. Both approaches create a new sorted dictionary.
