![]() |
VOOZH | about |
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.
1. Using sorted() with lambda: This method sorts the dictionary efficiently by its values using the sorted() function and a lambda expression.
{'watermelon': 1, 'apple': 2, 'banana': 3}
Explanation:
2. Using OrderedDict: This method sorts a dictionary by values and stores the result in an OrderedDict, which preserves insertion order.
OrderedDict({'tuesday': 9, 'monday': 10, 'wednesday': 15})
Explanation:
3. Using for loop with sorted(): This method sorts and displays dictionary values in ascending order using for loop with sorted() function.
(1, 2) (2, 56) (3, 323)
Explanation:
4. Using NumPy: This approach uses NumPy’s argsort() for fast value-based sorting in numerical dictionaries.
{'diana': 2, 'ben': 9, 'alex': 10, 'clara': 15, 'eva': 32}
Explanation:
1. Using sorted() with lambda: This method sorts the dictionary by its keys using sorted() and a lambda expression.
{'apple': 2, 'banana': 3, 'watermelon': 1}
Explanation:
2. Using OrderedDict: This method sorts dictionary items by key and stores them in an OrderedDict.
Explanation:
3. Using for loop with sorted(): This method sorts and prints dictionary items using key-based sorting.
Explanation:
4 Using NumPy: This method sorts the dictionary by converting keys to a NumPy array and using argsort() to get their sorted order.
{'alex': 10, 'ben': 9, 'clara': 15, 'diana': 2, 'eva': 32}
Explanation: