简体   繁体   English

聚合Python字典的布尔值的最佳方法是什么?

[英]What's the best way to aggregate the boolean values of a Python dictionary?

For the following Python dictionary: 对于以下Python字典:

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

I want to aggregate the boolean values above into the following boolean expression: 我想将上面的布尔值聚合到下面的布尔表达式中:

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

The above should return me False . 以上应该归还我的False I'm using keys with known names above but I want it to work so that there can be a large number of unknown key names. 我正在使用上面已知名称的密钥,但我希望它能够工作,以便可以存在大量未知的密钥名称。

in python 2.5+: 在python 2.5+中:

all(dict.itervalues())

in python 3+ 在python 3+中

all(dict.values())

dict is a bad variable name, though, because it is the name of a builtin type 但是, dict是一个糟糕的变量名,因为它是内置类型的名称

Edit: add syntax for python 3 version. 编辑:添加python 3版本的语法。 values() constructs a view in python 3, unlike 2.x where it builds the list in memory. values()在python 3中构造一个视图,与2.x不同,它在内存中构建列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在多个Python进程之间共享字典的最佳方法是什么? - What's the best way to share a dictionary between multiple Python processes? 在词典列表中搜索Python字典值的最佳方法是什么? - What's the best way to search for a Python dictionary value in a list of dictionaries? 在 Python 中跳过迭代变量的 N 个值的最佳方法是什么? - What's the best way of skip N values of the iteration variable in Python? 在Python中处理可选值的最佳方法是什么? - What's the best way to handle optional values in Python? Python:获取复杂字典值的最佳方法 - Python: The best way to get complex dictionary values 从Python中的字典获取值的最佳方法 - Best way to get values from a dictionary in Python 将python字典变成变量的最佳方法是什么? - What is the best way to turn a python dictionary into variables? 将字典键转换为具有字典值的变量的最佳方法是什么? - What is the best way to convert Dictionary keys into variables with the dictionary values? Python:基于值对python字典进行排序的最佳方法; 值是列表 - Python : Best way to sort a python dictionary based on values ; values are lists Python词典的价值是另一本词典-最好的方法? - Python dictionary's value is another dictionary — the best way?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM