Skip to content Skip to sidebar Skip to footer

Evaluate A Python String Expression Using Dictionary Values

I am parsing a text file which contain python 'string' inside it. For e.g.: 'my_home1' in houses.split(',') and '2018' in iphone.split(',') and 14 < mask for the example above,

Solution 1:

At the end I found a solution to my problem:

text = "'my_home1' in houses.split(',') and '2018' in iphone.split(',') and 14 < mask"
dict = {'house' : 'my_home1,my_home2', 'iphone' : '2015,2018', 'mask' : '15' }

expression = 'false'

for key in dict.keys():
    if isinstance(dict.get(key), str):
        text = re.sub(key, '\'{}\''.format(dict.get(key)), text)
    else:
        text = re.sub(key, dict.get(key), text)

eval(text)

Solution 2:

Is the following what you were expecting:

dict_ = {'house': 'my_home1,my_home2', 'iphone': '2015,2018'}
print('my_home1' in dict_['house'].split(',') and '2018' in dict_[
      'iphone'].split(',') and '2019' not in dict_['iphone'].split(','))

Post a Comment for "Evaluate A Python String Expression Using Dictionary Values"