- Python Sort by Two Keys
- Sorting In Python
- Sorting by Two Keys
- Sorting by Multiple Keys
- Sorting by Two Keys in Python
- 1. Sorting Dictionaries
- 2. Sorting Lists of Dictionaries
- Conclusion
- Sort by Two Keys in Python
- Sorting List of Tuples by Two Keys in Python
- Other Articles You’ll Also Like:
- About The Programming Expert
- Sort List or Dictionary by two keys in Python
- Sort list of dictionaries by multiple keys
- Sort List of Tuples by two keys in python
- Sort a dictionary by two keys in python
Python Sort by Two Keys
Sorting allow us to organize data in a meaningful way. Python provides several built-in functions and methods to sort data efficiently.
Sorting by one key is straightforward, but there are many situations where you need to sort data based on multiple criteria. For example:
- Sort a list of students based on their marks and then their names .
- Sort a list of employees based on their salary and then their age .
- Sort a list of athletes based on their score and then medals .
Sorting In Python
Before diving into sorting by two keys, let’s understand the basics of sorting in Python.
Python offers a versatile built-in function called sorted() that allows you to sort various data types such as lists, tuples, and dictionaries.
The sorted() function takes an iterable as its argument and returns a new sorted list. It doesn’t modify the original list, ensuring data integrity. By default, the sorted() function sorts elements in ascending order.
Let’s see how to use the sorted() function to sort a list of integers.
numbers = [5, 2, 3, 1, 4] # sort the list sorted_numbers = sorted(numbers) print(sorted_numbers)
Sorting by Two Keys
Above we have seen how to sort a list of integers. Now let’s see how to sort a list of tuples by two keys.
Suppose we have a list of tuples containing the name and marks of students.
students = [ ('John', 90), ('Alex', 80), ('Bob', 95), ('Alice', 85) ]
Now we want to sort this list by marks and then by name. To do this, we need to pass a key function to the sorted() function.
A key function is a function that takes an element as an argument and returns a value based on which the sorting is done.
Let’s see how to sort the above list by marks and then by name.
students = [('John', 90), ('Alex', 80), ('Bob', 95), ('Alice', 75)] # sort the list by marks and then by name sorted_students = sorted(students, key=lambda x: (x[1], x[0])) print(sorted_students)
[ ('Alice', 75), ('Alex', 80), ('John', 90), ('Bob', 95) ]
Here, we have passed a lambda function as a key function to the sorted() function. The lambda function takes a tuple as an argument and returns a tuple containing marks and name.
Since the sorted() function sorts elements in ascending order by default, the list is sorted by marks in ascending order.
If you want to sort the list by marks in descending order, you can pass reverse=True as an argument to the sorted() function.
students = [('John', 90), ('Alex', 80), ('Bob', 95), ('Alice', 75)] # sort the list by marks in descending order and then by name sorted_students = sorted(students, key=lambda x: (x[1], x[0]), reverse=True) print(sorted_students)
[ ('Bob', 95), ('John', 90), ('Alex', 80), ('Alice', 75) ]
Sorting by Multiple Keys
Now let’s see how to sort a list of tuples by multiple keys.
Suppose we have a list of tuples containing the name, age, and marks of students.
students = [ ('John', 20, 90), ('Alex', 18, 80), ('Bob', 19, 95), ('Alice', 20, 75) ]
Now we want to sort this list by age, marks, and then by name. To do this, we need to pass a key function to the sorted() function.
Let’s see how to sort the above list by age, marks, and then by name.
students = [ ('John', 20, 90), ('Alex', 18, 80), ('Bob', 19, 95), ('Alice', 20, 75) ] # sort the list by age, marks, and then by name sorted_students = sorted(students, key=lambda x: (x[1], x[2], x[0])) print(sorted_students)
[ ('Alex', 18, 80), ('Bob', 19, 95), ('Alice', 20, 75), ('John', 20, 90) ]
Sorting by Two Keys in Python
Let’s now see different variations of sorting by two keys in Python.
1. Sorting Dictionaries
Suppose we have a dictionary containing the name and marks of students.
Now we want to sort this dictionary by marks and then by name. To do this, we need to pass a key function to the sorted() function.
Let’s see how to sort the above dictionary by marks and then by name.
students = < 'John': 90, 'Alex': 80, 'Bob': 95, 'Alice': 85 ># sort the dictionary by marks and then by name sorted_students = sorted(students.items(), key=lambda x: (x[1], x[0])) print(sorted_students)
[ ('Alex', 80), ('Alice', 85), ('John', 90), ('Bob', 95) ]
2. Sorting Lists of Dictionaries
Suppose we have a list of dictionaries containing the computer parts, prices and ratings. Now we want to sort this list by price and then by rating.
products = [ , , , ] # sort the list by price and then by rating sorted_products = sorted(products, key=lambda x: (x['price'], x['rating'])) print(sorted_products)
Conclusion
In this article, we saw how to sort list, dictionary, and list of dictionaries by multiple keys in Python.
We looked at different variations of sorting by multiple keys in Python with examples.
By understanding these concepts, you can efficiently sort data based on multiple attributes in your Python projects.
- Can I sort by more than two keys in Python? Yes, you can sort by more than two keys in Python. Simply provide a tuple of keys to the key parameter, specifying the desired order of sorting.
- How do I specify the order of sorting for each key? To specify the order of sorting for each key, you can use the sorted() function with a custom key function. The key function should return a tuple of keys in the desired order.
- What happens if the keys have different data types? Python’s sorting mechanism is flexible and can handle different data types. However, it’s important to ensure that the keys are compatible and can be compared correctly.
- Is the order of the keys significant in Python sorting? Yes, the order of the keys is significant in Python sorting. The sorting process considers the keys in the order they are provided.
Sort by Two Keys in Python
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 = [, , , ] list_of_dicts.sort(key= lambda x: (x["weight"],x["name"])) print(list_of_dicts) #Output: [, , , ]
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 = [, , , ] list_of_dicts.sort(key= lambda x: (x["weight"],x["name"])) print(list_of_dicts) #Output: [, , , ]
You can achieve the same result with the sorted() function as well.
list_of_dicts = [, , , ] sorted_list_of_dicts = sorted(list_of_dict, key= lambda x: (x["weight"],x["name"])) print(sorted_list_of_dicts) #Output: [, , , ]
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.
Other Articles You’ll Also Like:
- 1. How to Add Commas to Numbers in Python
- 2. Cartesian Product of Two Lists in Python
- 3. How to Check if Variable Exists in Python
- 4. Using Python to Compare Strings Alphabetically
- 5. Using Python to Read Random Line from File
- 6. Get Month from Datetime in pandas DataFrame
- 7. pandas fillna – Replace NaN in Dataframe using Python
- 8. Read Last N Lines of File in Python
- 9. Keep Every Nth Element in List in Python
- 10. Length of Dictionary Python – Get Dictionary Length with len() Function
About The Programming Expert
The Programming Expert is a compilation of a programmer’s findings in the world of software development, website creation, and automation of processes.
Programming allows us to create amazing applications which make our work more efficient, repeatable and accurate.
At the end of the day, we want to be able to just push a button and let the code do it’s magic.
You can read more about us on our about page.
Sort List or Dictionary by two keys in Python
In this article, we will learn how to sort a list or dictionary using multiple keys in python.
Sorting a list or dictionary can be easily done using the sort() method and sorted() function in python.
However, if you want to sort a list or dictionary by multiple elements, let’s say two keys then the easiest way is to use the key parameter and tuple the keys that we want to sort.
Let’s see some examples to sort by two keys in Python.
Sort list of dictionaries by multiple keys
To sort a list of dictionaries we can use the sort() method in python.
Now to sort the list of objects by two keys:
Note: The key is an optional argument that is used to sort items by different criteria. It can take functions to determine the sorting of items.
- Next, pass the tuple of the keys that we want to sort by to the sorting lambda expression.
Let’s see an example to sort a list of employee dictionaries by two keys: name and salary using sort() function.
employee_list = [ 'name': 'Jack','salary':2000>, 'name': 'Danny','salary':1000>, 'name': 'Adam','salary':1500>, 'name': 'Bob','salary':1000>, ] employee_list.sort(key= lambda x: (x["salary"],x["name"])) print(employee_list)
In the above example, we have sorted the list of employee dictionaries by two keys: first by salary and second by the name key.
Sort List of Tuples by two keys in python
If you have a list of tuples and you want to sort the values using two keys in python, then we can use the sort() method and use a lambda function with the tuple to sort.
So to sort a list of tuples by two keys:
- Use the sort() method on the list.
- Use the key parameter and pass the lambda function.
- Now select the values in the tuple you want to sort by using its specific indices. Here we will sort by the first two elements, so the index are k[0] and k[1] .
tuple_list = [('a','c','b'),('b','c','a'),('a','b','d'),('c','a','b')] tuple_list.sort(key=lambda k: (k[0],k[1])) print(tuple_list)
This way you can sort tuples by multiple elements in python.
Sort a dictionary by two keys in python
To sort a dictionary by two keys we have to use the sorted() function and pass the lambda function to the key parameter.
emp_list = 'Jack':2000, 'Danny': 1000, 'Adam': 1500, 'Bob': 1000> sorted_list = sorted(emp_list, key= lambda x: (emp_list[x],x)) print(sorted_list)
It has printed out the list based on the salary and the name keys.
If you want to print out the salary along with the name in the output, we have to print out the results in tuple.
We can use the items() method of the dictionary object that returns the (key, value) tuple pair.
emp_list = 'Jack':2000, 'Danny': 1000, 'Adam': 1500, 'Bob': 1000> sorted_list = sorted(emp_list.items(), key= lambda x: (x[1],x[0])) print(sorted_list)
[('Bob', 1000), ('Danny', 1000), ('Adam', 1500), ('Jack', 2000)]
Here, the emp_list.items() returns the tuple with the key and value.
Next, we sorted the dictionary using two keys: salary and name of the employee.
Here, we have learned how to sort a list, dictionary, and tuple by multiple keys using the list’s sort() method and the sorted() function in python.
Other Articles You’ll Also Like: