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

python filter list of dictionaries by value
python filter nested dictionary
filter dictionary python by key
filter python
dictionary comprehension python
python filter string
python filter dictionary list lambda
python filter list of strings

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

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}

Python : Filter a dictionary by conditions on keys or values , The filtered dictionary i.e. newDict now contains filtered elements from the Iterate over all the key value pairs in dictionary and call the given Filter a dictionary to keep elements only whose values are string of length 6. In this article we will discuss different ways to filter contents from a dictionary by conditions on keys or value or on both. Suppose we have a dictionary in which int type element is key and string type elements are value i.e.

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.

Python, It contains well written, well thought and well explained computer science and Python | Filter dictionary key based on the values in selective list that we require to get only the selective dictionary keys from some given list. Filter a list based on the given list of strings � Python | Unique dictionary filter in� Python programming language provides filter() function in order to filter given array, list, dictionary or similar iterable struct. filter() function can be used to create iterable by filtering some elements of the given data.

input = {"A":"a", "B":"b", "C":"c"}
output = {k:v for (k,v) in input.items() if key_satifies_condition(k)}

Python, Sometimes, while working with dictionaries, we might have a use the exact keys we require but just a specific part of keys that we require to fetch. initializing search key string res = [val for key, val in test_dict.items() if search_key in key] In this, the dict and filter function is used to convert the result to� *** Python: check if key in dictionary using if-in statement*** Yes, key: 'test' exists in dictionary No, key: 'sample' does not exists in dictionary *** Python: check if dict has key using get() function *** No, key: 'sample' does not exists in dictionary No, key: 'sample' does not exists in dictionary python check if key in dict using keys

You can use the built-in filter function to filter dictionaries, lists, etc. based on specific conditions.

filtered_dict = dict(filter(lambda item: filter_str in item[0], d.items()))

The advantage is that you can use it for different data structures.

How To Filter Python List, Dictionary, Array, String List, Object , How To Filter Python List, Dictionary, Array, String List, Object Tutorial with Examples? filter() function can be used to create iterable by filtering some elements of the given data. This list contains numbers from 1 to the 9. Python | Filter dictionary key based on the values in selective list Last Updated: 21-02-2019 In Python, sometimes we require to get only some of the dictionary keys and not all.

Jonathon gave you an approach using dict comprehensions in his answer. Here is an approach that deals with your do something part.

If you want to do something with the values of the dictionary, you don't need a dictionary comprehension at all:

I'm using iteritems() since you tagged your question with python-2.7

results = map(some_function, [(k,v) for k,v in a_dict.iteritems() if 'foo' in k])

Now the result will be in a list with some_function applied to each key/value pair of the dictionary, that has foo in its key.

If you just want to deal with the values and ignore the keys, just change the list comprehension:

results = map(some_function, [v for k,v in a_dict.iteritems() if 'foo' in k])

some_function can be any callable, so a lambda would work as well:

results = map(lambda x: x*2, [v for k,v in a_dict.iteritems() if 'foo' in k])

The inner list is actually not required, as you can pass a generator expression to map as well:

>>> map(lambda a: a[0]*a[1], ((k,v) for k,v in {2:2, 3:2}.iteritems() if k == 2))
[4]

How to Filter a Dictionary in Python? (… The Most Pythonic Way , https://youtu.be/n4SOW80qpEs Problem: Given a dictionary and a filter condition. Method 4 — Dictionary comprehension {k:v for (k,v) in dict.items() if condition} is in the filtered dictionary newDict where the length of the name string value is thing as above—filtering by key to include only odd keys—you simply use the� Definition and Usage. The keys() method returns a view object. The view object contains the keys of the dictionary, as a list. The view object will reflect any changes done to the dictionary, see example below.

python filter a dictionary by keys or values � GitHub, shouldn't the if k in [2,3] be a v not a k on line 7 if filtering by value? Python | Extract specific keys from dictionary 15-05-2019 We have a lot of variations and applications of dictionary container in Python and sometimes, we wish to perform a filter of keys in dictionary, i.e extracting just the keys which are present in particular container.

Filter dictionary in a list, filter items in a python dictionary where keys contain a specific string , In Python 3 , there is only dict.items() , not iteritems() so you would use: If you want to do� Python Filter() Function. The filter() function accepts only two parameters. The first argument is the name of a user-defined function, and second is iterable like a list, string, set, tuple, etc.

Filtering Dictionary In Python 3, “RuntimeError: Dictionary changed size during iteration”, Python slaps you in your face when you try to add/remove entries in dict This is the least favorable solution, given that we have to create a new copy of the dictionary. Another solution is instead, create a copy of dictionary keys as our iterator:. In this tutorial, I’ll show you how to know if a string contains a substring. How to check if a string contains a substring. No matter whether it’s just a word, a letter or a phrase that you want to check in a string, with Python you can easily utilize the built-in methods and the membership test in operator.

Comments
  • stackoverflow.com/questions/2844516/python-filter-a-dictionary
  • Possible duplicate of How to filter a dictionary according to an arbitrary condition function?
  • Why not filtered_dict = {k:d[k] for k in d if filter_string in k}?
  • @thefourtheye I'm going to guess that mine is faster, as it doesn't incurrent the d[k] lookup.
  • Also, he says # do something in the comments, but we drop few keys here.
  • Do we have iteritems in Python 3? I don't think so. So, my version would be compatible, no?
  • In Python 3 you would replace iteritems with items, which is the same as Python 2.7's iteritems.
  • My method using iteritems() is going to be more efficient than items().
  • @Jonathin Reinhart I didn't knew about it. Thanks.
  • On Python 2.7 only. In Python 3 there is only items(), which acts like Python 2.7's iteritems.
  • The question is explicitly for python 2.7