所有None值的Python字典检查列表



我有以下字典列表,当前包含None值:

[{'connections': None}, {'connections': None}, {'connections': None}]

我想循环遍历元素列表,检查每个元素是否"连接"。key在每个字典中的值为None,如果是则返回true。如何检查所有值是否都为None?

您可以使用生成器表达式和all来解包lst中的所有dict值,并检查它们是否全部为None:

out = all(x is None for d in lst for x in d.values())

输出:

True

如果想在满足条件时进行静默检查:

dict_list = [{'connections': None}, {'connections': None}, {'connections': None}]
assert all( d['connections'] is None for d in dict_list), 'At least one connection value is not None'

如果条件不满足,则抛出AssertionError,并出现上述信息。否则,这一行将通过。

list =[{'connections': None}, {'connections': None}, {'connections': 
None}]
for item in list:
if(item['connections']==None):
return True

这里的for循环将获取每个元素,if语句将检查数组中每个元素的键值,因此如果它的None将返回True。

传递字典列表以检查包含所有None值的字典。

def func(list):
for dict in list:
for key in dict:
if dict[key] is not None:
return False

return True
print(func([{'connections': None}, {'connections': None}, {'connections': None}]))

简单地说,你可以使用键'connections'从字典与所有使用列表压缩

lst = [{'connections': None}, {'connections': None}, {'connections': None}]
if all([di.get('connections') == None for di in lst]):
print("All dict connections value None value")
else:
print("Some dict connections have not None value")

相关内容

  • 没有找到相关文章

最新更新