filter items in a python dictionary where keys contain a specific string?

You can filter items in a Python dictionary based on whether their keys contain a specific string using dictionary comprehension. Here’s an example:

original_dict = {'apple': 5, 'banana': 8, 'orange': 3, 'grape': 6}

# Specify the string you want to check for in the keys
specific_string = 'app'

# Use dictionary comprehension to filter items based on key containment
filtered_dict = {key: value for key, value in original_dict.items() if specific_string in key}


In this example, filtered_dict will contain only the items from original_dict whose keys contain the specified string (‘app’ in this case).

Adjust the specific_string variable to the string you want to check for, and the dictionary comprehension will create a new dictionary containing only the key-value pairs that meet the specified condition.

Leave a Reply

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