Python | Substring Key match in dictionary

Python | Substring Key match in dictionary

If you're looking to find all keys in a dictionary that contain a specific substring, you can use a dictionary comprehension along with the in keyword.

Here's a step-by-step guide on how to do this:

1. Sample Dictionary

data = { 'apple': 1, 'orangeapple': 2, 'banana': 3, 'grape': 4, 'applefruit': 5 } 

2. Find Keys with Substring

To find all keys that contain the substring 'apple':

substring = 'apple' matched_keys = [key for key, value in data.items() if substring in key] print(matched_keys) 

Output:

['apple', 'orangeapple', 'applefruit'] 

3. If You Want the Matched Key-Value Pairs

Instead of just the keys, if you want the corresponding key-value pairs for matched keys:

matched_items = {key: value for key, value in data.items() if substring in key} print(matched_items) 

Output:

{'apple': 1, 'orangeapple': 2, 'applefruit': 5} 

The dictionary comprehension iterates over all key-value pairs in the dictionary and checks if the key contains the specified substring. If it does, it includes the key (or key-value pair) in the resulting list (or dictionary).


More Tags

redux-form-validators pre-commit localization executable dyld onbeforeunload android-context imageurl atom-editor flask-migrate

More Programming Guides

Other Guides

More Programming Examples