still_learning
still_learning

Reputation: 806

Finding elements from a list included in another one

I have two lists

list_1=['mom','father','daughter','dog','soccer']
list_2=['beautiful mom','father day','snoop dog','Manchester United','Windows Office', 'Snoopy Dog']

and I would like to construct a relationship, whether a word from list_1 is in list_2. For example:

mom : ['beautiful mom']
father : ['father day']
daughter : []
dog : ['snoop dog', 'Snoopy Dog']
soccer : [] 

For each element in list_1 I need to look at list_2. If there the element is included, I add it in a list. I tried as follows:

set(list_1).issubset(list_2)

looking at subsets; but as I mentioned, my expected output would be something like this (in a pandas dataframe):

list_1         Match
mom        ['beautiful mom']
father     ['father day']
daughter   []
dog        ['snoop dog', 'Snoopy Dog']
soccer     [] 

Upvotes: 0

Views: 55

Answers (1)

Mark
Mark

Reputation: 92440

You can make an inverted index mapping individual words to phrases in list_2. Then it's just a matter of looking them up from list_1:

from collections import defaultdict

list_1=['mom','father','daughter','dog','soccer']
list_2=['beautiful mom','father day','snoop dog','Manchester United','Windows Office', 'Snoopy Dog']

index = defaultdict(list)

for v in list_2:
    for k in v.split():
        index[k.lower()].append(v)

res = {k:index[k.lower()] for k in list_1}

res will be:

{'mom': ['beautiful mom'],
 'father': ['father day'],
 'daughter': [],
 'dog': ['snoop dog', 'Snoopy Dog'],
 'soccer': []}

Upvotes: 1

Related Questions