How to Sort a Dictionary by Value in Python
How to Sort a Dictionary by Value in Python
How to Sort a Dictionary by Value in Python
I have a dictionary and I need to sort it based on its values. How can I achieve this in Python?
solveurit24@gmail.com Changed status to publish February 16, 2025
Sorting a dictionary by its values can be done using the sorted() function with a custom key.
- Using
sorted():- The
sorted()function returns a list of tuples sorted by the desired key.
- The
- Code Example:
my_dict = {'a': 3, 'b': 1, 'c': 2} sorted_items = sorted(my_dict.items(), key=lambda x: x[1]) sorted_dict = dict(sorted_items) print(sorted_dict) # Output: {'b': 1, 'c': 2, 'a': 3}
- Using the
itemgetterFunction:- The
itemgettercan also be used for more readability.
- The
- Alternative Code:
from operator import itemgetter my_dict = {'a': 3, 'b': 1, 'c': 2} sorted_items = sorted(my_dict.items(), key=itemgetter(1)) sorted_dict = dict(sorted_items) print(sorted_dict) # Output: {'b': 1, 'c': 2, 'a': 3}
- Explanation:
sorted()returns a list of tuples which can then be converted back to a dictionary.itemgetter(1)fetches the value for sorting.
solveurit24@gmail.com Changed status to publish February 16, 2025