Fetching Entries in Dictionary Based on Condition in Python
In Python, dictionaries provide a flexible way to store key-value pairs. Fetching entries in a dictionary based on a specific condition is a common task. This can be achieved using various methods, each with its advantages and use cases. In this article, we will explore different methods to fetch entries in a dictionary based on a condition.
Fetching Entries in a Dictionary Based on a Condition in Python
Below are some of the ways by which we can fetch entries in a dictionary based on a condition in Python:
- Using Dictionary Comprehension
- Using Filter() Function
- Using Items() Method with Loop
Fetching Entries in a Dictionary Using Dictionary Comprehension
In this example, we use dictionary comprehension to create a new dictionary (filtered_dict
) that contains only the entries with scores greater than or equal to 75. The condition (if value >= 75
) filters out entries that do not meet the criteria.
Python3
# initializing dictionary original_dict = { 'Alice' : 85 , 'Bob' : 72 , 'Charlie' : 90 , 'David' : 68 } filtered_dict = {key: value for key, value in original_dict.items() if value > = 75 } # Displaying the result print ( "Dictionary Comprehension:" , filtered_dict) |
Dictionary Comprehension: {'Alice': 85, 'Charlie': 90}
Filtering Entries in a Dictionary Using Filter() Function
In this method, a custom filtering function (filter_scores
) is defined, which returns True
if the value is greater than or equal to 75. The filter()
function is then applied to the items of the original dictionary, and the result is converted back to a dictionary using dict()
.
Python3
original_dict = { 'Alice' : 85 , 'Bob' : 72 , 'Charlie' : 90 , 'David' : 68 } # Define a filtering function def filter_scores(item): return item[ 1 ] > = 75 filtered_dict = dict ( filter (filter_scores, original_dict.items())) # Displaying the result print ( "Filter() Function:" , filtered_dict) |
Filter() Function: {'Alice': 85, 'Charlie': 90}
Filtering Entries in a Dictionary Using Items() Method
In this method, we iterate through the items of the original dictionary using a loop (for key, value in original_dict.items()
). Entries meeting the condition (if value >= 75
) are added to a new dictionary (filtered_dict
).
Python3
# initializing dictionary original_dict = { 'Alice' : 85 , 'Bob' : 72 , 'Charlie' : 90 , 'David' : 68 } filtered_dict = {} for key, value in original_dict.items(): if value > = 75 : filtered_dict[key] = value # Displaying the result print ( "Items() Method with Loop:" , filtered_dict) |
Items() Method with Loop: {'Alice': 85, 'Charlie': 90}