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} print(filtered_dict)
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.