Practical Use Cases and Examples
Now that we've covered the basics of list comprehension and how to use it to filter dictionary keys by their values, let's explore some practical use cases and examples.
Filtering Log Files
Imagine you have a log file containing various log entries, and you want to extract only the entries with a specific log level, such as "ERROR" or "WARNING". You can use list comprehension to achieve this:
log_entries = [
"2023-04-01 10:30:00 INFO: Application started",
"2023-04-01 10:30:15 ERROR: Database connection failed",
"2023-04-01 10:30:30 WARNING: Disk space running low",
"2023-04-01 10:30:45 INFO: User logged in"
]
error_logs = [entry for entry in log_entries if "ERROR" in entry]
warning_logs = [entry for entry in log_entries if "WARNING" in entry]
print("Error Logs:")
for log in error_logs:
print(log)
print("\nWarning Logs:")
for log in warning_logs:
print(log)
Output:
Error Logs:
2023-04-01 10:30:15 ERROR: Database connection failed
Warning Logs:
2023-04-01 10:30:30 WARNING: Disk space running low
Suppose you have a list of items, and you want to create a new list that contains only the unique values. You can use list comprehension to achieve this:
items = ["apple", "banana", "cherry", "banana", "date", "cherry"]
unique_items = list(set([item for item in items]))
print(unique_items)
Output:
['apple', 'banana', 'cherry', 'date']
In this example, the list comprehension [item for item in items]
creates a new list with all the items, and then the set()
function is used to remove the duplicates, and the result is converted back to a list.
Filtering Dictionaries by Multiple Conditions
You can also use list comprehension to filter dictionaries based on multiple conditions. For example, let's say you have a list of dictionaries representing student information, and you want to extract the names of students who scored above 90 and are in the age range of 18-22.
student_data = [
{"name": "Alice", "age": 20, "score": 92},
{"name": "Bob", "age": 19, "score": 88},
{"name": "Charlie", "age": 21, "score": 95},
{"name": "David", "age": 22, "score": 85},
{"name": "Eve", "age": 18, "score": 91}
]
high_scoring_students = [student["name"] for student in student_data if student["score"] > 90 and 18 <= student["age"] <= 22]
print(high_scoring_students)
Output:
['Alice', 'Charlie', 'Eve']
In this example, the list comprehension [student["name"] for student in student_data if student["score"] > 90 and 18 <= student["age"] <= 22]
creates a new list containing the names of students who scored above 90 and are in the age range of 18-22.
By understanding these practical use cases and examples, you can apply list comprehension to filter dictionary keys based on their values in a wide range of scenarios, making your Python code more concise and efficient.