How to Organize a Dictionary by Value: Top 5 Examples

How to Organize a Dictionary by Value: Top 5 Examples

You can sort a dictionary by its values using the sorted() function along with a custom key function that specifies to sort based on the values. Here's how you can do it along with five examples:

  1. Sorting a dictionary by values in ascending order:
my_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 3}
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print(sorted_dict)

Output:

{'banana': 2, 'grape': 3, 'apple': 5, 'orange': 8}
  1. Sorting a dictionary by values in descending order:
my_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'grape': 3}
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1], reverse=True))
print(sorted_dict)

Output:

{'orange': 8, 'apple': 5, 'grape': 3, 'banana': 2}
  1. Sorting a dictionary with string values:
my_dict = {'apple': 'c', 'banana': 'a', 'orange': 'd', 'grape': 'b'}
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print(sorted_dict)

Output:

{'banana': 'a', 'grape': 'b', 'apple': 'c', 'orange': 'd'}
  1. Sorting a dictionary with mixed value types:
my_dict = {'apple': 5, 'banana': 'a', 'orange': [1, 2, 3], 'grape': {'color': 'purple'}}
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: str(item[1])))
print(sorted_dict)

Output:

{'orange': [1, 2, 3], 'banana': 'a', 'apple': 5, 'grape': {'color': 'purple'}}
  1. Sorting a dictionary with duplicate values:
my_dict = {'apple': 5, 'banana': 2, 'orange': 5, 'grape': 3}
sorted_dict = dict(sorted(my_dict.items(), key=lambda item: item[1]))
print(sorted_dict)

Output:

{'banana': 2, 'grape': 3, 'apple': 5, 'orange': 5}

These examples demonstrate different scenarios of sorting dictionaries by their values.

Did you find this article valuable?

Support LingarajTechhub All About Programming by becoming a sponsor. Any amount is appreciated!