# Define a list of dictionaries my_list = [ {'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 30}, {'name': 'Bob', 'age': 20}, ] # Sort the list of dictionaries by the age value sorted_list = sorted(my_list, key=lambda x: x['age']) # Print the sorted list print(sorted_list)
[{'name': 'Bob', 'age': 20}, {'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 30}]
To sort a list of dictionaries by a value of the dictionary in Python, you can use the sorted() function. This function takes in the list of dictionaries and a key parameter, which specifies the dictionary key by which the list should be sorted.
You can also use the operator.itemgetter() function from the operator module as the key parameter. This can make the code more readable and efficient. Here is an example:
# Import the operator module import operator # Define a list of dictionaries my_list = [ {'name': 'John', 'age': 25}, {'name': 'Jane', 'age': 30}, {'name': 'Bob', 'age': 20}, ] # Sort the list of dictionaries by the age value sorted_list = sorted(my_list, key=operator.itemgetter('age')) # Print the sorted list print(sorted_list)This will produce the same output as the previous example.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.