Reputation: 15
I have a python dictionary of lists of phrases I would like to iterate through and print 1. the phrases containing a specified word ('first') and 2. The key they are associated with. I have come up with
Mydict = {'One': ['This is the first sentence', ' This is the next sentence after the first'], 'Two': ['This is the second first sentence', ' This is the second second sentence'], 'Three': ['This is the third sentence']}
def search(Mydict, lookup):
for key, value in Mydict.items():
for v in value:
if lookup in v:
return value, key
print(search(Mydict, 'first'))
Which prints:(['This is the first sentence', ' This is the next sentence after the first'], 'One')
I would like to get the result: ('This is the first sentence','One') ('This is the next sentence after the first','One') ('This is the second first sentence', 'Two')
I am not sure why what I have does not "catch" the third sentence I would like to get in the results. I am also not sure how to break up the lists within the dictionary and access each phrase individually. Thank you in advanced for any insight.
Upvotes: 1
Views: 55
Reputation: 1603
Just needed a couple small changes:
1: The reason you were only getting one match is because of your return statement. Since your function returns as soon as it finds a match, you'll only ever get the first match.
2: You were returning value, which is your entire list, instead of v, which is the matching item.
Updated code below
Mydict = {'One': ['This is the first sentence', ' This is the next sentence after the first'], 'Two': ['This is the second first sentence', ' This is the second second sentence'], 'Three': ['This is the third sentence']}
def search(Mydict, lookup):
for key, value in Mydict.items():
for v in value:
if lookup in v:
print((v, key))
search(Mydict, 'first')
Upvotes: 1