Matching Whole Dictionary Keys in String using List Comprehension

Question:

I have a dictionary called cc_dict and am trying to use list comprehension to iterate over each key to find a match in a string called new_string. The line below works but it also matches keys that are part of whole words. I want to match whole words only.

So, for example, the key "test" is matched in the string "text for testing".

How can I do this?

Example one:

cc_dict = {“test one”: “SSK1”, “result”: “TGG”, “pass”: “PSS1”, “fail”: “FL1”}

new_string = "If test one is complete."

output = [te for key, te in cc_dict.items() if key in new_string]

Desired result: SSK1

Example two:

cc_dict = {“test one”: “SSK1”, “result”: “TGG”, “pass”: “PSS1”, “fail”: “FL1”}

new_string = "There has been a failure in annex 1."

output = [te for key, te in cc_dict.items() if key in new_string]

Desired result: no result but as "fail" is contained in the word "failure" the list comprehension currently returns FL1.

Asked By: Andy

||

Answers:

If I understand correctly, you can split your match string into words using split:

[te for key, te in cc_dict.items() if key in new_string.split()]
Answered By: jprebys

You can try the following,

This method will use regex to determine if the whole string that you are looking for is available in the string that you are searching in,

def string_found(string1, string2):
    if re.search(r"b" + re.escape(string1) + r"b", string2):
        return True
    return False

This can now be used in your dict comprehension,

output = [te for key, te in cc_dict.items() if string_found(key, new_string)]

Results,

# scenario 1
cc_dict = {“test one”: “SSK1”, “result”: “TGG”, “pass”: “PSS1”, “fail”: “FL1”}

new_string = "If test one is complete."

output = [te for key, te in cc_dict.items() if string_found(key, new_string)]

output
>>['SSK1']

# scenario 2
cc_dict = {“test one”: “SSK1”, “result”: “TGG”, “pass”: “PSS1”, “fail”: “FL1”}

new_string = "There has been a failure in annex 1."

output = [te for key, te in cc_dict.items() if string_found(key, new_string)]

output
>>[]
Answered By: Minura Punchihewa
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.