Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Programming: how to eval values from dictionary?

Given string

str=" dept_id == CS1  and  student_count > 75 " 

Dictionary

dict = {'dept_id': 'CS1' ,'student_count': 95 }

We need to substitute values from dict in string and evaluate

eval (str)

code below works for all integer cases :

for item in dict.items():
k , v  = item
if s.find(k) > -1:
 k=str(k)
 s=s.replace(k, str(v),1)
 print "replaced",s

print eval(s)

Is there any other way to approach this problem?

like image 737
nkkrishnak Avatar asked Sep 14 '25 14:09

nkkrishnak


2 Answers

eval accepts an optional dictionary (globals, locals). You don't need to replace the string manually:

>>> s = "dept_id == 'CS1' and student_count > 75 "
>>> d = {'dept_id': 'CS1' ,'student_count': 95 }
>>> eval(s, d)
True
>>> d = {'dept_id': 'CS1' ,'student_count': 35 }
>>> eval(s, d)
False

BTW, using str, dict as variable names is not a good idea. They will shadows builtin function/types str, dict.

like image 73
falsetru Avatar answered Sep 17 '25 06:09

falsetru


Anyway, found this useful while trying to find solution to my problem with dictionary provided as string:

import ast # helps with converting str representation of python data structures
dictionary = "{'a':'a1', 'b':'a2', 'c':'a3' }"
parsed_dictionary = ast.literal_eval(dictionary)
>>> {'a':'a1', 'b':'a2', 'c':'a3'}

It may not be the exact answer for the problem, but might be helpful for somebody looking for safe solution or having similar problem to mine.

Using ast library:

The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

So as @IanAuld commented, I'd like to add that ast.literal_eval() is safer, because will raise an error while trying to parse string with structures other that listed above. Sure, eval() will delete data without hesitation ;) and I wouldn't recommend running this command.

like image 41
Jagoda Gorus Avatar answered Sep 17 '25 05:09

Jagoda Gorus