tristanojbacon tristanojbacon - 4 days ago 6
Python Question

Python: check if a dictionary item is in string, then return the match

I have a database table that looks like the following:

id phrases message
1 "social media, marketing" "This person is in marketing!"
2 "finance, fintech "This person is in finance!"


I've looped through the key phrases and added them to a dictionary, like so:

messages = self.db_access.execute("SELECT * FROM messages")
messages = self.db_access.fetchall()
print(len(messages))
if self.db_access.rowcount > 0:
has_message = True
phrase_list = {}
for the_rule in messages:
print(the_rule[1])
rule = the_rule[1].split(',')
for phrase in rule:
phrase = str(phrase)
phrase_list[phrase] = str(the_rule[2])
print(phrase_list)
print("\n")
else:
has_message = False


This then produces the following:

# phrase_list
{'social media': 'This person is in marketing!',
'marketing': 'This person is in marketing!',
'finance': 'This person is in finance!',
'fintech': 'This person is in finance!'}


So, each phrase has it's own accompanying message, which is used elsewhere.

Now, I can compare those dict keys against a string, like so:

descriptions = ["I am in marketing, and it is super awesome", "I am in finance, and it is super awesome"]


My next step is to compare that string with the keys, and if it contains any of the keywords, then print the matching key and its value/message. This is what I have so far:

for description in descriptions:
print(description)
if has_message == True:
if any(x in description for x in phrase_list):
# print matching keyword and message
else:
print("No matches, but a phrase list exists")


So my question is, what do I need to replace that comment with to output 1) the keyword it matched with, and 2) the message associated with that keyword?

Answer

You just have to restructure your code a bit. The need for that arouses from the use of any which does not return information on which x made the expression evaluate as True. It just tells you that someone did or that noone did. If you do care about which one you have to loop through or possibly use next. Anyway, here is one way to do it:

for description in descriptions:
    print(description)
    if has_message == True:
        for x in phrase_list:
            if x in description:
                print(x, phrase_list[x])
                break
        else:
            print("No matches, but a phrase list exists")

Note:

if the else on the for is confusing, just remove it. The code will reach it only if the x is not in any description anyway.

Comments