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.