Python: Sort a list of dictionaries using Lambda
Write a Python program to sort a list of dictionaries using Lambda.
Sample Solution:
Python Code :
# Create a list of dictionaries named 'models', each dictionary representing a mobile phone model with 'make', 'model', and 'color' keys
models = [
{'make': 'Nokia', 'model': 216, 'color': 'Black'},
{'make': 'Mi Max', 'model': '2', 'color': 'Gold'},
{'make': 'Samsung', 'model': 7, 'color': 'Blue'}
]
# Display a message indicating that the following output will show the original list of dictionaries
print("Original list of dictionaries:")
print(models)
# Sort the list of dictionaries ('models') based on the value associated with the 'color' key in each dictionary
# Uses the 'sorted()' function with a lambda function as the sorting key to sort based on the 'color' value
sorted_models = sorted(models, key=lambda x: x['color'])
# Display a message indicating that the following output will show the sorted list of dictionaries
print("\nSorting the List of dictionaries:")
print(sorted_models)
Sample Output:
Original list of dictionaries : [{'make': 'Nokia', 'model': 216, 'color': 'Black'}, {'make': 'Mi Max', 'model': '2', 'color': 'Gold'}, {'make': 'Samsung', 'model': 7, 'color': 'Blue'}] Sorting the List of dictionaries : [{'make': 'Nokia', 'model': 216, 'color': 'Black'}, {'make': 'Samsung', 'model': 7, 'color': 'Blue'}, {'make': 'Mi Max', 'model': '2', 'color': 'Gold'}]
Explanation:
In the exercise above the code initializes a list of dictionaries, each representing a mobile phone model with make, model, and color attributes. It then sorts this list of dictionaries based on the 'color' key's value in ascending order. It uses the sorted() function and a lambda function as the sorting key. Finally, it displays both the original list of dictionaries and the sorted list to the console.
Python Code Editor:
Have another way to solve this solution? Contribute your code (and comments) through Disqus.
Previous: Write a Python program to sort a list of tuples using Lambda.
Next: Write a Python program to filter a list of integers using Lambda.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics