1

I have a dictionary similar to this:

countries = ["usa", "france", "japan", "china", "germany"]
fruits = ["mango", "apple", "passion-fruit", "durion", "bananna"]

cf_dict = {k:v for k,v in zip(["countries", "fruits"], [countries, fruits])}

and I also have a list of strings similar to this:

docs = ["mango is a fruit that is very different from Apple","I like to travel, last year I was in Germany but I like France.it was lovely"]

I would like to inspect the docs and see if each string contains any of the keywords in any of the lists(the values of cf_dict are lists) in cf_dict, and if they are present then return the corresponding key(based on values) for that string(strings in docs) as output.

so for instance, if I inspect the list docs the output will be [fruits, countries]

something similar to this answer but this checks only one list, however, I would like to check multiple lists.

ultron
  • 442
  • 8
  • 16

1 Answers1

2

The following returns a dict of sets in case a string matches values in more than one list (e.g. 'apple grows in USA' should be mapped to {'fruits', 'countries'}).

print({s: {k for k, l in cf_dict.items() for w in l if w in s.lower()} for s in docs})

This outputs:

{'mango is a fruit that is very different from Apple': {'fruits'}, 'I like to travel, last year I was in Germany but I like France.it was lovely': {'countries'}}
blhsing
  • 91,368
  • 6
  • 71
  • 106