Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/19.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/mercurial/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python3一行程序,用于验证字典值中是否存在项_Python_Python 3.x_Dictionary - Fatal编程技术网

Python3一行程序,用于验证字典值中是否存在项

Python3一行程序,用于验证字典值中是否存在项,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我正在寻找一个可能的一班轮返回相当于 'A' in ['A', 'B', 'C'] 但在以下情况下: 假设我有一个包含列表作为值的字典,如: dictionary = {'key1': ['A', 'B', 'C', 'D'], 'key2': ['E', 'F'], 'key3': ['G', 'H', 'I']} 到目前为止,我能得到的最接近的结果是: r = {v[0] for k, v in dictionary.items

我正在寻找一个可能的一班轮返回相当于

'A' in ['A', 'B', 'C']
但在以下情况下: 假设我有一个包含列表作为值的字典,如:

dictionary = {'key1': ['A', 'B', 'C', 'D'], 
              'key2': ['E', 'F'], 
              'key3': ['G', 'H', 'I']}
到目前为止,我能得到的最接近的结果是:

r = {v[0] for k, v in dictionary.items() if 'A' in v}
但是,这将返回一组长度为0或1的元素,返回我要检查的列表元素

关于字典值中存储的任何列表中是否存在“A”,我只想得到True/False。

您需要内置函数:

any('A' in v for v in dictionary.values())

any()
在遇到真实命题时立即返回
True
本身是最佳选择,但如果您想进一步提高性能,可以使用
set
对象而不是列表来保留其成员资格检查的值,这是线性的

如果您想在找到匹配项后停止迭代所有dict值,请使用
itertools.takewhile

import itertools
if list(itertools.takewhile(lambda v: 'J' in v, dictionary.values())):
    # Found
else:
    # Not found