python - Storing logical conditions in a dictionary and passing them to if statements -
i have dictionary of logical conditions, i.e. == 1, need use in if statement evaluation. may not possible, wanted find out sure. sample code:
z = {'var1':['a == 1'], 'var2':['b == 3'] } = 6 b = 20 #if use dictionary value in if statement this: if z['var1']: print 'true' else: print 'false' #it evaluate true. want statement #translate following form: if == 1: print 'true' else: print 'false'
i have been searching various permutations on if statements, list comprehensions , string manipulation, haven't found results matching problem. if not possible, i'd know. if there better approach, i'd know well. in advance answers.
you trying store expression, possible use built-in eval()
function (you can use exec
if want play around statements).
>>> = 6 >>> b = 3 >>> z = { 'var1':eval('a == 1'), 'var2':eval('b == 3'), } >>> if z['var1']: print "true!" else: print "false!" false! >>> if z['var2']: print "true!" else: print "false!" true!
note need assign variables before create expressions inside dictionary, expression evaluated @ run-time, nameerror
exception raised if variable doesn't exist in memory.
>>> eval(foo) nameerror: name 'foo' not defined
also wary eval()
can dangerous if allow users input arbitrary strings argument. more here.
to explain why original code returning true
, boolean expression if
statement evaluating list containing 1 string. python evaluates non-empty sequences true
, satisfy condition , string true printed.
>>> z['var1'] ['a == 1'] >>> bool(z['var1']) true
Comments
Post a Comment