dict to boolean expression, how to?

Alex van der Spek zdoor at xs4all.nl
Fri Aug 1 10:26:38 EDT 2014


On Fri, 01 Aug 2014 12:45:12 +0000, 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

I am sorry, the problem is ill posed.

'a', 'A' and so forth are my failed attempt to shorthand.

In reality the dict's keys are column names in a pandas dataframe df.

The boolean expression would therefore look like:

bool = ((df['a'] == 1) & (df['A'] == 0) |
         (df['b'] == 1) & (df['B'] == 0) |
         (df['c'] == 1) & (df['C'] == 0))

I do know eval() lends itself to code injection but can't say I am
fully aware of its dangers. It seemed like a handy tool to me.

This newsgroup scares me, it appears to be for professional computer 
scientists only, the theoretical part is sometimes too much for this 
practical physicist with an old background in FORTRAN.

Is there a better place to ask questions of this nature?

Alex van der Spek



More information about the Python-list mailing list