dict to boolean expression, how to?

Ned Batchelder ned at nedbatchelder.com
Fri Aug 1 10:29:10 EDT 2014


On 8/1/14 8:45 AM, Alex van der Spek wrote:
> With a dict like so:
>
> cond = {'a': 1, 'b': 1, 'c': 1,
>          'A': 0, 'B', 0, 'C':0}
>
> how would you make a boolean expression like this:
>
> bool = (('a' == 1) & ('A' == 0) |
>          ('b' == 1) & ('B' == 0) |
>          ('c' == 1) & ('C' == 0))
>
> The fact that lowercase and uppercase keys are stringed together with & is
> intentional albeit the actual condition is a bit more tricky.
>
> I've tried several approaches using eval() on a string built from the dict
> but landed with just spelling it out literally.
>
>
> Any pointers welcome.
> Alex
>

Are you looking for this?

     bool = (
         (cond['a'] == 1 and cond['A'] == 0) or
         (cond['b'] == 1 and cond['B'] == 0) or
         (cond['c'] == 1 and cond['C'] == 0)
     )

If so, what's wrong with that expression exactly?  I'm not sure how eval 
could enter into it, so I feel like I'm missing something.

-- 
Ned Batchelder, http://nedbatchelder.com




More information about the Python-list mailing list