更新时间:2022-01-04 06:22:18
这里是一种方法:
if not any(d['main_color'] == 'red' for d in a):
# does not exist
括号中的部分是一个生成器表达式,对于具有要查找的键值对的每个词典,返回True
,否则返回False
.
The part in parentheses is a generator expression that returns True
for each dictionary that has the key-value pair you are looking for, otherwise False
.
如果密钥也可能丢失,则上面的代码可以为您提供KeyError
.您可以使用get
并提供默认值来解决此问题.
If the key could also be missing the above code can give you a KeyError
. You can fix this by using get
and providing a default value.
if not any(d.get('main_color', None) == 'red' for d in a):
# does not exist