2

I try to check all values from a dictionary with multiple criteria. With this code there is no probleme for check if all values are equal to 1 for exemple :

config = {"a": 1, "b": 1, "c": 1, "d": 3, "e": 2}

if all(value == 1 for value in config.values()):
    print('correct')
else:
    print('wrong')

But now if want to add some operator in this code to check if all values are 1 Or 2 Or 3 for example results aren't working like i want :

config = {"a": 1, "b": 1, "c": 1, "d": 3, "e": 5}

if all(value == (1 or 2 or 3) for value in config.values()):
    print('correct')
else:
    print('wrong')

>>>correct

I've also try many variations like :

if all(value == 1 or 2 or 3 for value in config.values()):
if all((value == 1 or 2 or 3) for value in config.values()):
if all(value for value in config.values() == 1 or 2 or 3):
...

So how to use correctly these operators to make this work please ?

Adrien
  • 63
  • 8
  • 1
    Try `if all(value in [1, 2, 3] for value in config.values()):`, which is a bit shorter way of writing `if all((value == 1 or value == 2 or value == 3) for value in config.values()):` – 0x5453 Jun 28 '19 at 20:55
  • 1
    You can do `all(value in [1,2,3] for value in config.values())`, but what you're really doing here is set math, so use sets: `{1, 2, 3}.issuperset(config.values())`. – kojiro Jun 28 '19 at 20:57
  • Thank's this is perfect. – Adrien Jun 28 '19 at 21:00

1 Answers1

2

What you have inside all is a generator expression (which can be replaced with any iterable), so use it like one:

all(value in {1, 2, 3} for value in config.values())

value == (1 or 2 or 3) isn't working because it is being treated as:

value = 1

1 or 2 or 3 will return 1*, so all the values are being compared for eqality with 1.

* An or chain will return the first truthy value or the last value in the chain as the default (irrespective of it's truthiness).

heemayl
  • 39,294
  • 7
  • 70
  • 76