Python dict list complex sorting—sort+lambda

Complex Sorting of Python Dict Lists—sort+lambda

Complex Sorting of Python Dict Lists—sort+lambda

In Python, we often need to sort lists or dictionaries. Typically, for simple sorting requirements, we can use the built-in function sorted(). However, for complex sorting requirements, we need to use the sort() method combined with a lambda function.

This article details how to use the sort() method and lambda functions to sort complex lists of dictionaries. We’ll start with basic sorting and gradually introduce more complex sorting rules to help you fully understand how to handle different sorting needs.

Basic Sorting

First, let’s look at a simple example: sorting a list of integers. Suppose we have the following list:

numbers = [5, 3, 8, 1, 6, 2, 7, 4]

<p>We can use the <code>sort() method to sort it in ascending order:

numbers.sort()
print(numbers)

The result of running this function is:

[1, 2, 3, 4, 5, 6, 7, 8]

If we want to sort in descending order, we can pass in the reverse=True parameter:

numbers.sort()
print(numbers)
numbers.sort(reverse=True)
print(numbers)

The output is:

[8, 7, 6, 5, 4, 3, 2, 1]

We can also use a similar method to sort a list of dictionaries. Suppose we have the following list of dictionaries:

students = [
{"name": "Alice", "age": 20},
{"name": "Bob", "age": 18},
{"name": "Charlie", "age": 22}
]

We can sort by a key in the dictionary, for example, by age in ascending order:

students.sort(key=lambda x: x["age"])
print(students)

The output is:

[{'name': 'Bob', 'age': 18}, {'name': 'Alice', 'age': 20}, {'name': 'Charlie', 'age': 22}]

Complex Sorting

Single Sorting Rule

In the above example, we used only one sorting rule. However, in real applications, we may need multiple sorting rules. In this case, we can use a lambda function combined with the sort() method to implement it.

Suppose we have the following list of dictionaries and need to sort them in ascending order by name. If the names are the same, we need to sort them in descending order by age:

students = [
{"name": "Alice", "age": 20},
{"name": "John", "age": 18},
{"name": "Alice", "age": 22}
]

We can implement complex sorting with the following code:

students.sort(key=lambda x: (x["name"], -x["age"]))
print(students)

The result is:

[{'name': 'Alice', 'age': 22}, {'name': 'Alice', 'age': 20}, {'name': 'John', 'age': 18}]

In the lambda function, we use a tuple (x["name"], -x["age"]) as the sort key, where x["name"] is used to sort by name, and -x["age"] is used to sort by age in descending order.

Multiple Sorting Rules

If we need more sorting rules, for example, we can sort by name in ascending order, then sort by age in descending order if the names are the same, and then sort by grades in ascending order if the ages are the same. We can implement this in a similar way:

students = [
{"name": "Alice", "age": 20, "score": 85},
{"name": "John", "age": 18, "score": 75},
{"name": "Alice", "age": 22, "score": 80}
]

students.sort(key=lambda x: (x["name"], -x["age"], x["score"]))
print(students)

The output is:

[{'name': 'Alice', 'age': 22, 'score': 80}, {'name': 'Alice', 'age': 20, 'score': 85}, {'name': 'John', 'age': 18, 'score': 75}]

In the lambda function, we use a tuple (x["name"], -x["age"], x["score"]) as the sort key, where x["name"] is used to sort by name, -x["age"] is used to sort by age in descending order, and x["score"] is used to sort by grade in ascending order.

Sorting Order

In the above examples, we use the default ascending sorting order. However, sometimes we may need to specify the sorting order, for example, sorting by grade in descending order. In this case, we can use the reverse=True parameter to specify the sorting order.

Suppose we have the following list of dictionaries and need to sort them in descending order by grade:

students = [
{"name": "Alice", "age": 20, "score": 85},
{"name": "John", "age": 18, "score": 75},
{"name": "Alice", "age": 22, "score": 80}
]

students.sort(key=lambda x: x["score"], reverse=True)
print(students)

The output is:

[{'name': 'Alice', 'age': 20, 'score': 85}, {'name': 'Alice', 'age': 22, 'score': 80}, {'name': 'John', 'age': 18, 'score': 75}]

In the sort() method, we passed the reverse=True parameter to specify descending sort order by grade.

Summary

This article detailed how to use the sort() method and the lambda function to sort complex lists of dictionaries. We started with basic sorting and gradually introduced the application of various sorting rules and sorting orders. We hope this article will help readers better understand and master sorting operations in Python.

Note that the sort() method directly modifies the original list. If you want to preserve the original list, use the sorted() function and assign the result to a new list.

Leave a Reply

Your email address will not be published. Required fields are marked *