Sort List of Dictionaries by Multiple Keys - Python
Last Updated :
28 Jan, 2025
We are given a list of dictionaries where each dictionary contains various keys and our task is to sort the list by multiple keys. Sorting can be done using different methods such as using the sorted() function, a list of tuples, itemgetter() from the operator module. For example, if we have the following list of dictionaries: d= [ {'name': 'Aryan', 'age': 25, 'score': 90}, {'name': 'Harsh', 'age': 22, 'score': 95}, {'name': 'Kunal', 'age': 25, 'score': 85}]. The output after sorting by age and score will be: [ {'name': 'Harsh', 'age': 22, 'score': 95}, {'name': 'Kunal', 'age': 25, 'score': 85}, {'name': 'Aryan', 'age': 25, 'score': 90}]
Using sorted() Function
sorted() function is a built-in Python function that sorts any iterable and returns a new sorted list. It can be used with a custom sorting key to sort dictionaries based on multiple keys. By passing a lambda function we can sort the list of dictionaries based on multiple keys such as age and score.
Python
data = [
{'name': 'Aryan', 'age': 25, 'score': 90},
{'name': 'Harsh', 'age': 22, 'score': 95},
{'name': 'Kunal', 'age': 25, 'score': 85}
]
a = sorted(data, key=lambda x: (x['age'], x['score']))
print(a)
Output[{'name': 'Harsh', 'age': 22, 'score': 95}, {'name': 'Kunal', 'age': 25, 'score': 85}, {'name': 'Aryan', 'age': 25, 'score': 90}]
Explanation: lambda x: (x['age'], x['score']) defines the sorting criteria where the list is first sorted by age and then by score and sorted() returns a new list leaving the original list unchanged.
Using List of Tuples
In this method we create a list of tuples where each tuple contains the values of the keys we want to sort by followed by the original dictionary. This list of tuples is then sorted based on the values of the keys and the sorted dictionaries are extracted from the tuples.
Python
data = [
{'name': 'Aryan', 'age': 25, 'score': 90},
{'name': 'Harsh', 'age': 22, 'score': 95},
{'name': 'Kunal', 'age': 25, 'score': 85}
]
t = sorted([(x['age'], x['score'], x) for x in data])
d = [x[2] for x in t]
print(d)
Output[{'name': 'Harsh', 'age': 22, 'score': 95}, {'name': 'Kunal', 'age': 25, 'score': 85}, {'name': 'Aryan', 'age': 25, 'score': 90}]
Explanation:
- [(x['age'], x['score'], x) for x in data] creates the list of tuples with age, score and the dictionary x.
- list is sorted by the first two elements in the tuple and the original dictionary is retrieved with [x[2] for x in t].
Using itemgetter() Method
In this method we use itemgetter from the operator module to sort the list of dictionaries by multiple keys such as age and score.
Python
from operator import itemgetter
data = [
{'name': 'Aryan', 'age': 25, 'score': 90},
{'name': 'Harsh', 'age': 22, 'score': 95},
{'name': 'Kunal', 'age': 25, 'score': 85}
]
d = sorted(data, key=itemgetter('age', 'score'))
print(d)
Output[{'name': 'Harsh', 'age': 22, 'score': 95}, {'name': 'Kunal', 'age': 25, 'score': 85}, {'name': 'Aryan', 'age': 25, 'score': 90}]
Similar Reads
Python | Sort given list of dictionaries by date Given a list of dictionary, the task is to sort the dictionary by date. Let's see a few methods to solve the task. Method #1: Using naive approach Python3 # Python code to demonstrate # sort a list of dictionary # where value date is in string # Initialising list of dictionary ini_list = [{'name':'a
2 min read
Python - Sort dictionaries list by Key's Value list index Given list of dictionaries, sort dictionaries on basis of Key's index value. Input : [{"Gfg" : [6, 7, 8], "is" : 9, "best" : 10}, {"Gfg" : [2, 0, 3], "is" : 11, "best" : 19}, {"Gfg" : [4, 6, 9], "is" : 16, "best" : 1}], K = "Gfg", idx = 0 Output : [{'Gfg': [2, 0, 3], 'is': 11, 'best': 19}, {'Gfg': [
14 min read
Python | Sort nested dictionary by key Sorting has quite vivid applications and sometimes, we might come up with a problem in which we need to sort the nested dictionary by the nested key. This type of application is popular in web development as JSON format is quite popular. Let's discuss certain ways in which this can be performed. Met
4 min read
Sort a List of Python Dictionaries by a Value Sorting a list of dictionaries by a specific value is a common task in Python programming. Whether you're dealing with data manipulation, analysis, or simply organizing information, having the ability to sort dictionaries based on a particular key is essential. In this article, we will explore diffe
3 min read
Python | Sort dictionary keys to list Sometimes, we wish to flatten the dictionary into list, the simple flattening is relatively easier, but when we wish to align keys and values in sorted way, i.e sorted by value, then it becomes quite a complex problem. Let's discuss certain ways in which this task can be performed. Method #1 : Using
4 min read
Python Sort Nested Dictionary by Multiple Values We are given a nested dictionary and our task is to sort a nested dictionary by multiple values in Python and print the result. In this article, we will see how to sort a nested dictionary by multiple values in Python. Example: Input : {'A': {'score': 85, 'age': 25}, 'B': {'score': 92, 'age': 30}, '
3 min read
Python - Convert List to List of dictionaries We are given a lists with key and value pair we need to convert the lists to List of dictionaries. For example we are given two list a=["name", "age", "city"] and b=[["Geeks", 25, "New York"], ["Geeks", 30, "Los Angeles"], ["Geeks", 22, "Chicago"]] we need to convert these keys and values list into
4 min read
Filter List of Python Dictionaries by Key in Python In Python, filtering a list of dictionaries based on a specific key is a common task when working with structured data. In this article, weâll explore different ways to filter a list of dictionaries by key from the most efficient to the least.Using List Comprehension List comprehension is a concise
3 min read
Filtering a List of Dictionary on Multiple Values in Python Filtering a list of dictionaries is a common task in programming, especially when dealing with datasets. Often, you may need to extract specific elements that meet certain criteria. In this article, we'll explore four generally used methods for filtering a list of dictionaries based on multiple valu
4 min read
Python program to sort Dictionary by Key Lengths Given Dictionary, sort by its key lengths. Input : test_dict = {"Gfg" : 4, "is" : 1, "best" : 0, "for" : 3, "geeks" : 3} Output : {'is': 1, 'Gfg': 4, 'for': 3, 'best': 0, 'geeks': 3} Explanation : 2 < 3 = 3 < 4 < 5, are sorted lengths in order. Input : test_dict = {"Gfg" : 4, "for" : 3, "ge
4 min read