What is the best way to combine the logical values ​​of a Python dictionary?

For the following Python dictionary:

dict = { 'stackoverflow': True, 'superuser': False, 'serverfault': False, 'meta': True, } 

I want to aggregate the booleans above into the following boolean expression:

 dict['stackoverflow'] and dict['superuser'] and dict['serverfault'] and dict['meta'] 

The above should return me False . I use keys with the well-known names above, but I want it to work so that there can be a large number of unknown key names.

+7
python
source share
1 answer

in python 2.5 +:

 all(dict.itervalues()) 

in python 3+

 all(dict.values()) 

dict is the name of a bad variable, although it is a built-in type name

Edit: add syntax for python version 3. values() creates a view in python 3, unlike 2.x, where it builds a list in memory.

+23
source share

All Articles