pythondictionaryfiltermembershipany

Filter a dictionary with a list of strings


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} 

Solution

  • 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}