Junior
208
How to sort a list of dictionaries by a specific field?
Answer from AI
sobes.tech AI
To sort a list of dictionaries by a specific field, you can use the sorted() function with the key parameter or the list method .sort().
Example with sorted():
# Original list of dictionaries
data = [
{'name': 'Bob', 'age': 30},
{'name': 'Alice', 'age': 25},
{'name': 'Charlie', 'age': 35}
]
# Sorting by the 'age' field
sorted_data = sorted(data, key=lambda x: x['age'])
# print(sorted_data) # Output the sorted list
Example with .sort():
# Original list of dictionaries
data = [
{'name': 'Bob', 'age': 30},
{'name': 'Alice', 'age': 25},
{'name': 'Charlie', 'age': 35}
]
# Sorting the list in place by the 'name' field
data.sort(key=lambda x: x['name'])
# print(data) # Output the sorted list
Both approaches use an anonymous lambda function that extracts the key value for sorting. The sorted() function returns a new sorted list, while .sort() sorts the list in place.
You can also use the operator.itemgetter function for a more concise syntax:
import operator
# Original list of dictionaries
data = [
{'name': 'Bob', 'age': 30},
{'name': 'Alice', 'age': 25},
{'name': 'Charlie', 'age': 35}
]
# Sorting by 'age' using itemgetter
sorted_data = sorted(data, key=operator.itemgetter('age'))
# print(sorted_data) # Output the sorted list
For reverse sorting, add the reverse=True parameter:
import operator
# Original list of dictionaries
data = [
{'name': 'Bob', 'age': 30},
{'name': 'Alice', 'age': 25},
{'name': 'Charlie', 'age': 35}
]
# Sorting by 'age' in reverse order
sorted_data_reverse = sorted(data, key=operator.itemgetter('age'), reverse=True)
# print(sorted_data_reverse) # Output the list sorted in reverse