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

dictionary, filtering, python, python-2.7

Solution

How about a dict comprehension:

filtered_dict = {k:v for k,v in d.iteritems() if filter_string in k}

One you see it, it should be self-explanatory, as it reads like English pretty well.

This syntax requires Python 2.7 or greater.

In Python 3, there is only `dict.items()`, not `iteritems()` so you would use:

filtered_dict = {k:v for (k,v) in d.items() if filter_string in k}

Problem

I'm a C coder developing something in python. I know how to do the following in C (and hence in C-like logic applied to python), but I'm wondering what the 'Python' way of doing it is. I have a dictionary d, and I'd like to operate on a subset of the items, only those whose key (string) contains a specific substring. i.e. the C logic would be: ``` for key in d: if filter_string in key: # do something else # do nothing, continue ``` I'm imagining the python version would be something like ``` filtered_dict = crazy_python_syntax(d, substring) for key,value in filtered_dict.iteritems(): # do something ``` I've found a lot of posts on here regarding filtering dictionaries, but couldn't find one which involved exactly this. My dictionary is not nested and i'm using python 2.7

Original source

Related problems