How to filter dictionary keys by substring in Python?

How can I filter items in a Python dictionary where the keys contain a specific substring?

I’m a C programmer transitioning to Python, and I’m familiar with how this can be done in C. In C, I would iterate over the dictionary (or hash map) and check if the key contains a specific substring. If it does, I’d perform an operation; otherwise, I’d skip it.

For example, in C-like logic, it would look like this:

for (key in dictionary) {
    if (filter_string in key) {
        // do something
    } else {
        // do nothing, continue
    }
}

I’m wondering what the Pythonic way of doing this is.

For instance, I’m thinking that the Python equivalent might look like this:

filtered_dict = crazy_python_syntax(d, substring)
for key, value in filtered_dict.iteritems():
    # do something

I’ve seen many posts on filtering dictionaries, but none that exactly deal with filtering based on whether the keys contain a specific substring.

Note: I’m using Python 2.7.

I’ve worked with Python dictionaries extensively, and one of the most Pythonic ways to handle this is by using dictionary comprehension. It’s clean, efficient, and easy to read:

filtered_dict = {key: value for key, value in d.items() if substring in key}  
for key, value in filtered_dict.items():  
    # do something  

This method works well when you want a quick and elegant way to filter your dictionary based on keys containing a specific substring.

Adding to Tim’s approach, if you prefer a functional programming style or need to combine this with other operations, you can use the filter function along with the dict constructor.

Here’s how it looks:

filtered_dict = dict(filter(lambda item: substring in item[0], d.items()))  
for key, value in filtered_dict.items():  
    # do something  

This method is particularly useful if you’re already using functional programming techniques in your code, and it fits seamlessly with pipelines or other transformations.

Sometimes, you might want more explicit control over the filtering process. In those cases, a manual for loop works perfectly. While it’s slightly longer, it can be more flexible if you need to add extra logic.

filtered_dict = {}  
for key, value in d.items():  
    if substring in key:  
        filtered_dict[key] = value  
for key, value in filtered_dict.items():  
    # do something  

This approach might feel a bit more verbose, but it’s great if you need to debug or extend your filtering logic with additional conditions.