In this tutorial, we will guide you through sorting a list of dictionaries based on the maximum value of each dictionary.
Scenario: Suppose we have a list of dictionaries:
data = [{"a": 10, "b": 15, "c": 7}, {"a": 8, "b": 20, "c": 3}, {"a": 12, "b": 5, "c": 11}] We aim to sort the data based on the maximum value in each dictionary in descending order. The desired output for the above data would be:
[{"a": 8, "b": 20, "c": 3}, {"a": 10, "b": 15, "c": 7}, {"a": 12, "b": 5, "c": 11}] Steps:
sorted() function.Python Code:
def sort_dicts_based_on_max_value(data): """ Sort a list of dictionaries based on the maximum value of each dictionary. :param data: List of dictionaries. :return: List of dictionaries sorted based on maximum value in descending order. """ # Step 1: Use the `sorted()` function return sorted(data, key=lambda x: max(x.values()), reverse=True) # Example usage: data = [{"a": 10, "b": 15, "c": 7}, {"a": 8, "b": 20, "c": 3}, {"a": 12, "b": 5, "c": 11}] sorted_data = sort_dicts_based_on_max_value(data) for d in sorted_data: print(d) Explanation:
sort_dicts_based_on_max_value that takes a list of dictionaries named data as input.sorted() function to sort the list.key parameter of the sorted() function is a lambda function that returns the maximum value of each dictionary using the max() function and the values() method of the dictionary.reverse=True argument sorts the list in descending order.By leveraging the power of Python's built-in functions like sorted() and max(), this approach provides an effective way to sort a list of dictionaries based on the maximum value.
angular-ui-bootstrap apache-spark-1.5 xcode7 subset-sum flying-saucer xorg absolute xquery alter-table network-programming