Reputation: 227
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.
Upvotes: 1
Views: 535
Reputation: 67
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']
Upvotes: 0
Reputation: 36624
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']
Upvotes: 0
Reputation: 187
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)
Upvotes: 0
Reputation: 5012
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']
Upvotes: 1
Reputation: 24233
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']
Upvotes: 2