How to Sort a Dictionary by Value in Python

88 views

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
0

Sorting a dictionary by its values can be done using the sorted() function with a custom key.

  1. Using sorted():
    • The sorted() function returns a list of tuples sorted by the desired key.
  2. 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}
    


  3. Using the itemgetter Function:
    • The itemgetter can also be used for more readability.
  4. 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}
    


  5. 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
0