1

How to search if a substring is matching to the dict value,

I am able to match the whole string with dict value, but how can we match the substring and the value in the dict.

EX = {
      'TYPE_1': ['abc'],
      'TYPE_2': ['bbc' , 'lmn'],
      'TYPE_3': ['abcde'],
      'TYPE_4': ['dcvabc']
      }

m1 = "Hi abc , welcome"
m2 = "This i new session named: dcvabc"
m3 = "welcome to the class lmn"

Expecting output as below:

if m1 string is compared it must return key TYPE_1
if m2 string is compared it much return key TYPE_4
if m2 string is compared it much return key TYPE_2

Please suggest on this.

Hancy
  • 71
  • 4
  • Oh, wait a minute, your expected output for `m2` is *word matching*, not *substring matching*, otherwise it would match `'TYPE_1'` as well. See [Find substring in string but only if whole words?](https://stackoverflow.com/q/4154961/4518341) – wjandrea Aug 16 '20 at 18:43

1 Answers1

0
EX = {
      'TYPE_1': ['abc'],
      'TYPE_2': ['bbc' , 'lmn'],
      'TYPE_3': ['abcde'],
      'TYPE_4': ['dcvabc']
      }

m1 = "Hi abc , welcome"
m2 = "This i new session named: dcvabc"
m3 = "welcome to the class lmn"


m1_out = [key for (key, lst) in EX.items() for ele in lst if ele in m1]
m2_out = [key for (key, lst) in EX.items() for ele in lst if ele in m2]
m3_out = [key for (key, lst) in EX.items() for ele in lst if ele in m3]
Andreas
  • 8,694
  • 3
  • 14
  • 38