Home > Mobile >  How to grep between two lists and output key pairs of 'search_term' : 'item_found
How to grep between two lists and output key pairs of 'search_term' : 'item_found

Time:06-10

I have two lists, I want to use list1 as search terms in list2 and return both the search term and the "hit"

list1 = ["dog", "cat", "mouse"]

list2 = ["bigdog", "blackcat", "horse"]

I can find occurrences of list1 items in list2 like this:

def find_in_list(list1, list2):
    matches = []

    for i in list1:
        match = filter(lambda x:i in x, list2)
        matches.extend(match)

    return(matches)

This will output ['bigdog', 'blackcat'], however I want to know which search term found the match in list2, and have output like this:

{'bigdog': 'dog', 'blackcat': 'cat'}

CodePudding user response:

I think this is what you want to get

list1 = ["dog", "cat", "mouse"]

list2 = ["bigdog", "blackcat", "horse"]

def find_in_list(list1, list2):
    matches = []

    for i in list1:
        match = filter(lambda x:i in x, list2)
        matches.extend(match)

    return(matches)

result = find_in_list(list1, list2)
dict_result = dict(zip(result,list1))
print(dict_result)
# Output: {'bigdog': 'dog', 'blackcat': 'cat'}

CodePudding user response:

This most straightforward way is this. Just iterate through each item, and when you see one string is in the other, just add it to the dictionary:

my_dict = {}
for item1 in list1:
    for item2 in list2:
        if item1 in item2:
            my_dict[item2] = item1
print(my_dict)

This is what was printed:

$ python dict_words.py 
{'bigdog': 'dog', 'blackcat': 'cat'}
  • Related