Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 513
memo Avatar asked May 26 '14 03:05

memo


People also ask

How do you filter a dictionary value in Python?

Filter Python Dictionary By Key Using Generic Function The lambda function you pass returns k%2 == 1 which is the Boolean filtering value associated with each original element in the dictionary names .

How do you check if a dictionary has a specific key?

You can check if a key exists or not in a dictionary using if-in statement/in operator, get(), keys(), handling 'KeyError' exception, and in versions older than Python 3, using has_key().

How do you filter a dictionary key in a list Python?

How do I filter a dictionary list in Python? Short answer: The list comprehension statement [x for x in lst if condition(x)] creates a new list of dictionaries that meet the condition. All dictionaries in lst that don't meet the condition are filtered out. You can define your own condition on list element x .


2 Answers

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} 
like image 97
Jonathon Reinhart Avatar answered Sep 17 '22 08:09

Jonathon Reinhart


Go for whatever is most readable and easily maintainable. Just because you can write it out in a single line doesn't mean that you should. Your existing solution is close to what I would use other than I would user iteritems to skip the value lookup, and I hate nested ifs if I can avoid them:

for key, val in d.iteritems():     if filter_string not in key:         continue     # do something 

However if you realllly want something to let you iterate through a filtered dict then I would not do the two step process of building the filtered dict and then iterating through it, but instead use a generator, because what is more pythonic (and awesome) than a generator?

First we create our generator, and good design dictates that we make it abstract enough to be reusable:

# The implementation of my generator may look vaguely familiar, no? def filter_dict(d, filter_string):     for key, val in d.iteritems():         if filter_string not in key:             continue         yield key, val 

And then we can use the generator to solve your problem nice and cleanly with simple, understandable code:

for key, val in filter_dict(d, some_string):     # do something 

In short: generators are awesome.

like image 33
Brendan F Avatar answered Sep 19 '22 08:09

Brendan F