简体   繁体   中英

Python: Filter a dictionary key using list of strings

I have a dictionary that contains a key with a list of values that are strings.

d = {'docs':['1_a', '2_a', '3_b', '4_c', '4_d']}

I'd like to filter d['docs'] with a filter list like ['a', '4'] , so that I get:

['1_a', '2_a', '4_c', '4_d']

The filter list could have numerous keywords not just two. I've looked in to list comprehension and failed.

Just search if any of the search terms appear in your values:

d = {'docs':['1_a', '2_a', '3_b', '4_c', '4_d']}
search = ['a', '4']
out = [val for val in d['docs'] if any(s in val for s in search)]

print(out)
# ['1_a', '2_a', '4_c', '4_d']

Here you go:

>>> d = {'docs':['1_a', '2_a', '3_b', '4_c', '4_d']}
>>> search = ['a', '4']
>>> [x for x in d['docs'] if any(s in x for s in search)]
['1_a', '2_a', '4_c', '4_d']

I came up with a solution, not sure if it is what you're looking for.

d = {'docs':['1_a', '2_a', '3_b', '4_c', '4_d']}
filter = ['a', '4']
result = []

for i in (d['docs']):
    
    for f in filter:
        if f in i:
            result.append(i)

print(result)

在此处输入图像描述

You can also use filter() to filter elements from a list:

list(filter(lambda x: any(i in x for i in ['a', '4']), d['docs']))
['1_a', '2_a', '4_c', '4_d']

Looks like the OP got what they wanted, but this is mostly typed so I might as well post it. If the idea is to work with slugs then the accepted answer could cause strange results.

For example:

>>> d = {'docs': ['2_at', '2_hat', '34_b', '4_c', '32_bat']}
>>> search = ['at', '4']
>>> [val for val in d['docs'] if any(s in val for s in search)]
['2_at', '2_hat', '34_b', '4_c', '32_bat']

Instead, you could split each item:

>>> d = {'docs': ['2_at', '2_hat', '34_b', '4_c', '32_bat']}
>>> search = ['at', '4']
>>> [val for val in d['docs'] if any(s in val.split('_') for s in search)]
['2_at', '4_c']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM