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
Python - Get items in sorted order from given dictionary
Python dictionaries contain key-value pairs that are unordered by default. Often, we need to display or process dictionary items in sorted order based on their keys. This article explores different methods to sort dictionary items.
Using operator.itemgetter()
The operator module provides itemgetter() function which can extract specific elements from tuples. Using itemgetter(0) sorts by keys, while itemgetter(1) sorts by values ?
import operator
data = {12: 'Mon', 21: 'Tue', 17: 'Wed'}
print("Given dictionary:", data)
print("Sorted by keys:")
for key, value in sorted(data.items(), key=operator.itemgetter(0)):
print(key, "->", value)
Given dictionary: {12: 'Mon', 21: 'Tue', 17: 'Wed'}
Sorted by keys:
12 -> Mon
17 -> Wed
21 -> Tue
Sorting by Values
To sort by values instead of keys, use itemgetter(1) ?
import operator
data = {12: 'Mon', 21: 'Tue', 17: 'Wed'}
print("Sorted by values:")
for key, value in sorted(data.items(), key=operator.itemgetter(1)):
print(key, "->", value)
Sorted by values: 12 -> Mon 21 -> Tue 17 -> Wed
Using sorted() on Dictionary Keys
The sorted() function can be applied directly to dictionary keys to get them in ascending order ?
data = {12: 'Mon', 21: 'Tue', 17: 'Wed'}
print("Given dictionary:", data)
print("Values in key-sorted order:")
for key in sorted(data):
print(data[key])
Given dictionary: {12: 'Mon', 21: 'Tue', 17: 'Wed'}
Values in key-sorted order:
Mon
Wed
Tue
Using sorted() on dict.items()
The most common and readable approach is to sort dict.items(), which returns both keys and values in sorted order ?
data = {12: 'Mon', 21: 'Tue', 17: 'Wed'}
print("Given dictionary:", data)
print("Sorted items (key-value pairs):")
for key, value in sorted(data.items()):
print(key, value)
Given dictionary: {12: 'Mon', 21: 'Tue', 17: 'Wed'}
Sorted items (key-value pairs):
12 Mon
17 Wed
21 Tue
Reverse Sorting
Add reverse=True parameter for descending order ?
data = {12: 'Mon', 21: 'Tue', 17: 'Wed'}
print("Sorted in descending order:")
for key, value in sorted(data.items(), reverse=True):
print(key, value)
Sorted in descending order: 21 Tue 17 Wed 12 Mon
Comparison
| Method | Returns | Best For |
|---|---|---|
operator.itemgetter() |
Key-value pairs | Complex sorting logic |
sorted(dict) |
Keys only | When you only need keys |
sorted(dict.items()) |
Key-value pairs | Most readable and common |
Conclusion
Use sorted(dict.items()) for the most readable approach to sort dictionary items by keys. For custom sorting logic, use operator.itemgetter() with appropriate index parameters.
