Python Dictionary Sort by Value: A Step-by-Step Guide
Sort a Python Dictionary by Value
Want to order your dictionary items based on their values? This tutorial shows you how using Python's built-in functions and a clear example.
def sort_dictionary_by_value(dictionary):
sorted_dict = dict(sorted(dictionary.items(), key=lambda item: item[1]))
return sorted_dict
# Example dictionary
my_dict = {'apple': 5, 'banana': 2, 'orange': 8, 'grapes': 3}
# Sorting the dictionary by value
sorted_dict = sort_dictionary_by_value(my_dict)
# Printing the sorted dictionary
for key, value in sorted_dict.items():
print(key, value)
Explanation:
-
sort_dictionary_by_value(dictionary)Function:- This function takes a dictionary as input.
- Inside, it uses the
sorted()function to sort the dictionary's items (key-value pairs). - The
key=lambda item: item[1]part is crucial: it tellssorted()to use the second element of each item (which is the value) for sorting. - Finally, it converts the sorted list of tuples back into a dictionary using
dict()and returns the sorted dictionary.
-
Example Usage:
- We create a sample dictionary
my_dict. - We call
sort_dictionary_by_value()to get the sorted dictionary. - We then loop through the
sorted_dictand print each key-value pair.
- We create a sample dictionary
Key Points:
- Dictionaries themselves are unordered, so this code creates a new sorted dictionary.
- You can modify the
my_dictwith your own data to test it out. - This approach is efficient and widely used in Python for sorting dictionaries by values.
原文地址: https://www.cveoy.top/t/topic/TAW 著作权归作者所有。请勿转载和采集!