To sort a list of objects by two keys in Python, the easiest way is with the key parameter and a tuple of the keys you want to sort by.
list_of_dicts = [{"name":"Bob","weight":100,"height":50},
{"name":"Sally","weight":120,"height":70},
{"name":"Jim","weight":120,"height":60},
{"name":"Larry","weight":150,"height":60}]
list_of_dicts.sort(key= lambda x: (x["weight"],x["name"]))
print(list_of_dicts)
#Output:
[{'name': 'Bob', 'weight': 100, 'height': 50}, {'name': 'Jim', 'weight': 120, 'height': 60}, {'name': 'Sally', 'weight': 120, 'height': 70}, {'name': 'Larry', 'weight': 150, 'height': 60}]
The Python sort() and sorted() functions allow us to sort collections of data.
One such situation where we need to do a little more work to get the result we want is if we want to sort our data by two keys.
To sort a list of objects by two keys in Python, the easiest way is with the key parameter and a tuple of the keys you want to sort by.
Just pass the keys you want to sort by as a tuple for your sorting lambda expression.
Below is a simple example showing you how to sort a list of dictionaries by two keys in Python.
list_of_dicts = [{"name":"Bob","weight":100,"height":50},
{"name":"Sally","weight":120,"height":70},
{"name":"Jim","weight":120,"height":60},
{"name":"Larry","weight":150,"height":60}]
list_of_dicts.sort(key= lambda x: (x["weight"],x["name"]))
print(list_of_dicts)
#Output:
[{'name': 'Bob', 'weight': 100, 'height': 50}, {'name': 'Jim', 'weight': 120, 'height': 60}, {'name': 'Sally', 'weight': 120, 'height': 70}, {'name': 'Larry', 'weight': 150, 'height': 60}]
You can achieve the same result with the sorted() function as well.
list_of_dicts = [{"name":"Bob","weight":100,"height":50},
{"name":"Sally","weight":120,"height":70},
{"name":"Jim","weight":120,"height":60},
{"name":"Larry","weight":150,"height":60}]
sorted_list_of_dicts = sorted(list_of_dict, key= lambda x: (x["weight"],x["name"]))
print(sorted_list_of_dicts)
#Output:
[{'name': 'Bob', 'weight': 100, 'height': 50}, {'name': 'Jim', 'weight': 120, 'height': 60}, {'name': 'Sally', 'weight': 120, 'height': 70}, {'name': 'Larry', 'weight': 150, 'height': 60}]
Sorting List of Tuples by Two Keys in Python
If you have a list of tuples and want to sort these tuples, you can take the example from above and modify it slightly.
To sort a list of tuples by the first and second element, for example, you will pass the first and second element for your tuple to the lambda function.
Below is an example of how you can sort a list of tuples by two keys in Python.
list_of_tuples= [(3, 5, 9),(1, 2, 3),(2, 5, 7),(1, 2, 4),(2, 3, 6)]
list_of_tuples.sort(key= lambda x: (x[0],x[1]))
print(list_of_tuples)
#Output:
[(1, 2, 3), (1, 2, 4), (2, 3, 6), (2, 5, 7), (3, 5, 9)]
Hopefully this article has been useful for you to learn how to sort a list of objects by two keys in Python.