Given a dictionary in Python, the task is to sort it by key or value, either in ascending or descending order. For Example:
Input: {'apple': 5, 'banana': 2, 'cherry': 7}
Output: {'banana': 2, 'apple': 5, 'cherry': 7}
Explanation: The dictionary is sorted by values in ascending order, since 2 < 5 < 7, the order becomes {'banana': 2, 'apple': 5, 'cherry': 7}.
Let's explore different methods to sort dictionary by key or value in Python.
Sorting by Value
1. Using sorted() with lambda: This method sorts the dictionary efficiently by its values using the sorted() function and a lambda expression.
d = {'watermelon': 1, 'apple': 2, 'banana': 3}
asc = {k: v for k, v in sorted(d.items(), key=lambda item: item[1])}
print(asc)
Output
{'watermelon': 1, 'apple': 2, 'banana': 3}
Explanation:
- sorted(d.items(), key=lambda item: item[1]): sorts by values (ascending).
- Dictionary comprehension rebuilds the sorted dictionary.
2. Using OrderedDict: This method sorts a dictionary by values and stores the result in an OrderedDict, which preserves insertion order.
from collections import OrderedDict
d = {'monday': 10, 'tuesday': 9, 'wednesday': 15}
res = OrderedDict(sorted(d.items(), key=lambda item: item[1]))
print(res)
Output
OrderedDict({'tuesday': 9, 'monday': 10, 'wednesday': 15})
Explanation:
- sorted(d.items(), key=lambda item: item[1]): sorts using the value of each key-value pair.
- OrderedDict(): stores the sorted order so it stays preserved.
3. Using for loop with sorted(): This method sorts and displays dictionary values in ascending order using for loop with sorted() function.
d = {2: 56, 1: 2, 3: 323}
for k, v in sorted(d.items(), key=lambda item: item[1]):
print((k, v), end=" ")
Output
(1, 2) (2, 56) (3, 323)
Explanation:
- sorted(d.items(), key=lambda item: item[1]): sorts dictionary by values.
- Loop prints key-value pairs in ascending order of their values.
4. Using NumPy: This approach uses NumPy’s argsort() for fast value-based sorting in numerical dictionaries.
import numpy as np
d = {'alex': 10, 'ben': 9, 'clara': 15, 'diana': 2, 'eva': 32}
k = list(d.keys())
v = list(d.values())
idx = np.argsort(v)
res = {k[i]: v[i] for i in idx}
print(res)
Output
{'diana': 2, 'ben': 9, 'alex': 10, 'clara': 15, 'eva': 32}
Explanation:
- np.argsort(v): returns indices that would sort the values.
- Dictionary comprehension rebuilds a new dictionary in value-sorted order.
Sorting by Key
1. Using sorted() with lambda: This method sorts the dictionary by its keys using sorted() and a lambda expression.
d = {'watermelon': 1, 'apple': 2, 'banana': 3}
asc = {k: v for k, v in sorted(d.items(), key=lambda item: item[0])}
print(asc)
Output
{'apple': 2, 'banana': 3, 'watermelon': 1}
Explanation:
- key=lambda item: item[0] → sorts using keys.
- Dictionary comprehension rebuilds the key-sorted dictionary.
2. Using OrderedDict: This method sorts dictionary items by key and stores them in an OrderedDict.
from collections import OrderedDict
d = {'monday': 10, 'tuesday': 9, 'wednesday': 15}
res = OrderedDict(sorted(d.items(), key=lambda item: item[0]))
print(res)
Explanation:
- sorted(d.items(), key=lambda item: item[0]): sorts by key.
- OrderedDict() preserves the sorted order.
3. Using for loop with sorted(): This method sorts and prints dictionary items using key-based sorting.
d = {2: 56, 1: 2, 3: 323}
for k, v in sorted(d.items(), key=lambda item: item[0]):
print((k, v), end=" ")
Explanation:
- sorted(d.items(), key=lambda item: item[0]): sorts by key.
- Loop prints key-value pairs in ascending key order.
4 Using NumPy: This method sorts the dictionary by converting keys to a NumPy array and using argsort() to get their sorted order.
import numpy as np
d = {'alex': 10, 'ben': 9, 'clara': 15, 'diana': 2, 'eva': 32}
k = list(d.keys())
v = list(d.values())
idx = np.argsort(k)
res = {k[i]: v[i] for i in idx}
print(res)
Output
{'alex': 10, 'ben': 9, 'clara': 15, 'diana': 2, 'eva': 32}
Explanation:
- np.argsort(k): returns indices that sort the keys alphabetically.
- Dictionary comprehension builds the key-sorted dictionary.