Question
Asked By – memo
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 who’s 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
Now we will see solution for issue: filter items in a python dictionary where keys contain a specific string
Answer
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}
This question is answered By – Jonathon Reinhart
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0