Python Programming: how to eval values from dictionary?
Solution 1
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
.
Solution 2
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.
nkkrishnak
Updated on June 13, 2022Comments
-
nkkrishnak almost 2 years
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?