Horje
Sort List of Dictionaries Python by Multiple Keys

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 sorted(), using a list of tuples, utilizing the collections.OrderedDict class, and employing the itemgetter from the operator module.

Sort List of Dictionaries Python by Multiple Keys

Below, are the ways to Sort List of Dictionaries Python by Multiple Keys.

Create a Dictionary

Below, the code defines a list of dictionaries called ‘data’ with information about individuals (name, age, and score), and then prints the entire list.

Python3

# Sample list of dictionaries
data = [
    {'name': 'John', 'age': 25, 'score': 90},
    {'name': 'Alice', 'age': 22, 'score': 95},
    {'name': 'Bob', 'age': 25, 'score': 85}
]
print(data)

Output:

[{'name': 'John', 'age': 25, 'score': 90}, 
{'name': 'Alice', 'age': 22, 'score': 95},
{'name': 'Bob', 'age': 25, 'score': 85}]

Sort List of Dictionaries Python Using sorted() Function

In this example, below code sorts the ‘data’ list of dictionaries first by ‘age’ and then by ‘score’, and prints the resulting sorted list.

Python3

# 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}]

Sort List of Dictionaries Python Using List of Tuple

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.

Python3

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}]

Sort List of Dictionaries Python Using 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.

Python3

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}]

Sort List of Dictionaries Python Using itemgetter() Method

In 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.

Python3

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

Related
Join Elements of a Set into a String in Python Join Elements of a Set into a String in Python
Filter List Of Dictionaries in Python Filter List Of Dictionaries in Python
Python Print Dictionary Keys and Values Python Print Dictionary Keys and Values
Sort Nested Dictionary by Value Python Descending Sort Nested Dictionary by Value Python Descending
How To Install Pytz In Python? How To Install Pytz In Python?

Type:
Geek
Category:
Coding
Sub Category:
Tutorial
Uploaded by:
Admin
Views:
12