dicts列表中的第一个非null值



让我们假设我想在这个dicts列表中获得key的第一个,该值不是null:

arr = [
{
"key": None,
"anotherkey": 0
},
{
"another": "ignore"
},
{
"bool": True,
"key": "this!"
}
]

有一条班轮可以做这件事吗?我用for循环做的。

您可以循环内部字典,并使用next:中的生成器表达式检查不是Nonekey

>>> next((d['key'] for d in arr if d.get('key') is not None), None)
'this!'

这将返回与'key'相关联的第一个值,否则,如果不存在这样的键/值对,则返回None

最新更新