![]() |
Python offers various methods to sort a list of dictionaries by multiple keys. This is a common task when dealing with data where you need to order elements based on different criteria. In this article, we will explore four different approaches: using Sort List of Dictionaries Python by Multiple KeysBelow, are the ways to Sort List of Dictionaries Python by Multiple Keys.
Create a DictionaryBelow, the code defines a list of dictionaries called ‘data’ with information about individuals (name, age, and score), and then prints the entire list. Python3
Output: [{'name': 'John', 'age': 25, 'score': 90}, Sort List of Dictionaries Python Using
|
# Sort the list by 'age' and then by 'score' sorted_data = sorted (data, key = lambda x: (x[ 'age' ], x[ 'score' ])) # Print the sorted result print (sorted_data) |
Output
[{'name': 'Alice', 'age': 22, 'score': 95},
{'name': 'Bob', 'age': 25, 'score': 85},
{'name': 'John', 'age': 25, 'score': 90}]
In this example, below code creates a list of tuples where each tuple contains ‘age’, ‘score’, and the corresponding dictionary from the original ‘data’. It then sorts these tuples based on the first two elements (‘age’, ‘score’) and extracts the original dictionaries to form the sorted list.
sorted_data_tuples = sorted ([(x[ 'age' ], x[ 'score' ], x) for x in data]) # Extract the dictionaries from the sorted tuples sorted_data = [x[ 2 ] for x in sorted_data_tuples] # Print the sorted result print (sorted_data) |
Output
[{'name': 'Alice', 'age': 22, 'score': 95},
{'name': 'Bob', 'age': 25, 'score': 85},
{'name': 'John', 'age': 25, 'score': 90}]
collections.OrderedDict
In this example, below code sorts the 'data' list of dictionaries based on the order of keys, first by 'age' and then by 'score', using `OrderedDict`. The resulting sorted list is then printed.
from collections import OrderedDict # Sort the list by 'age' and then by 'score' using OrderedDict sorted_data = sorted (data, key = lambda x: OrderedDict( sorted (x.items()))) # Print the sorted result print (sorted_data) |
Output:
[{'name': 'Alice', 'age': 22, 'score': 95},
{'name': 'Bob', 'age': 25, 'score': 85},
{'name': 'John', 'age': 25, 'score': 90}]
itemgetter
() MethodIn this example, below code uses the `itemgetter` from the `operator` module to sort the ‘data’ list of dictionaries first by ‘age’ and then by ‘score’, and then prints the resulting sorted list.
from operator import itemgetter # Sort the list by 'age' and then by 'score' using itemgetter sorted_data = sorted (data, key = itemgetter( 'age' , 'score' )) # Print the sorted result print (sorted_data) |
Output :
[{'name': 'Alice', 'age': 22, 'score': 95},
{'name': 'Bob', 'age': 25, 'score': 85},
{'name': 'John', 'age': 25, 'score': 90}]
Reffered: https://www.geeksforgeeks.org
Python |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |