0

I am trying to search a dictionary for a list of words and output the matched words in the dictionary and key. Here is my workable code:

word_search = 'sun'
text_dict = {'1: This is the sun.',  2: 'Tomorrow will be windy', 3: 'I went to the park.'}
bin = []

for key, value in text_dict.items():
  if word_search in value:
  bin.append(key)
  bin.append(word_search)
return bin
Output: [1, sun]

This works with single string 'sun'. How can I make a LIST work in this function?

word_search = ['sun', 'park']
Output: TypeError: 'in <string>' requires string as left 

Thanks!

luna
  • 11
  • 1

1 Answers1

0

You can use a loop and in operators to determine if elements in the list exist in the key,value pair.

[(key, word) for word in word_search for key, value in text_dict.items() if word in value]
#[(1, 'sun'), (3, 'park')]
PacketLoss
  • 5,561
  • 1
  • 9
  • 27