2

I have a dictionary that looks something like:

d= {'GAAP':[True,True],'L1':[True,False],'L2':[True,True]}

I would like to perform a logical AND operation across each of the values in the dictionary and return a LIST of True/False values. Something like:

for counter in range(0,2):
    print(d['GAAP'][counter] & d['L1'][counter] & d['L2'][counter])

My dictionary is fairly large so want to avoid manually typing each of the keys to perform the logical AND.

Georgy
  • 6,348
  • 7
  • 46
  • 58
Number Logic
  • 668
  • 1
  • 6
  • 17
  • 1
    Note: Your `&` actually is the bitwise, not logical AND. And also you don't have to type all keys manually, just use the `d.keys()` method (or `d.values()`, as you are only interested in the values anyway). – Niklas Mertsch May 31 '20 at 09:23
  • Does this answer your question? [Are there builtin functions for elementwise boolean operators over boolean lists?](https://stackoverflow.com/questions/2770434/are-there-builtin-functions-for-elementwise-boolean-operators-over-boolean-lists). Note that the best answer to your question there is actually in the question itself. – Georgy May 31 '20 at 09:42

1 Answers1

5

One way would be to use zip to get all corresponding elements and then to ask if they are all true:

map(all, zip(*d.values()))

Result it: [True, False]

Gilad Green
  • 34,248
  • 6
  • 46
  • 76
  • 1
    Very efficient solution! Note that `map(...)` does not return a list, but is lazily evaluated, just like `zip(...)`, so to get a list of the results, you need to wrap `list(...)` around that. – Niklas Mertsch May 31 '20 at 09:24
  • @NiklasMertsch - that is true. Was contemplating if to add that to the answer or not :) – Gilad Green May 31 '20 at 09:30