Home > OS >  Filter a dictionary with a list of strings
Filter a dictionary with a list of strings

Time:07-03

I have a dictionary where every key and every value is unique. I'd like to be able to filter based on a list of strings. I've seen lot of examples with the key is consistent but not where its unique like in the example below.

thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964} 
filt = ["rand", "ar"]

result

{"brand": "Ford","year": 1964} 

CodePudding user response:

I assume that the key of the dict should be contained in any filter value. Accordingly, my solution looks like this:

thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964} 
filt = ["rand", "ar"]

def matches(filter, value):
    return any(x in value for x in filter)

def filter(dict, filt):
    return {k: v for k, v in dict.items() if matches(filt, k)}

print(filter(thisdict, filt))

Output:

{'brand': 'Ford', 'year': 1964}

Or shortened:

thisdict = { "brand": "Ford", "model": "Mustang", "year": 1964} 
filt = ["rand", "ar"]

filtered = {k: v for k, v in thisdict.items() if any(x in k for x in filt)}

print(filtered)

Output:

{'brand': 'Ford', 'year': 1964}

CodePudding user response:

Use any() function to search for partially matching keys.

# use any to search strings in filt among keys in thisdict
{k:v for k,v in thisdict.items() if any(s in k for s in filt)}
# {'brand': 'Ford', 'year': 1964}
  • Related