Filter a Dictionary Based on Certain Conditions in Python

Filtering a dictionary based on certain conditions allows you to extract specific key-value pairs that meet specific criteria. In this blog post, we will explore different methods to filter a dictionary based on certain conditions in Python.

Method 1: Using a dictionary comprehension

# Method 1: Using a dictionary comprehension
my_dict = {"a": 10, "b": 5, "c": 20, "d": 15}
filtered_dict = {key: value for key, value in my_dict.items() if value > 10}

print("Filtered Dictionary:", filtered_dict)

Output:

Filtered Dictionary: {‘c’: 20, ‘d’: 15}

Method 2: Using the filter() function

# Method 2: Using the filter() function
my_dict = {"a": 10, "b": 5, "c": 20, "d": 15}
filtered_dict = dict(filter(lambda item: item[1] > 10, my_dict.items()))

print("Filtered Dictionary:", filtered_dict)

Output:

Filtered Dictionary: {‘c’: 20, ‘d’: 15}