让我们假设我想在这个dicts列表中获得key
的第一个值,该值不是null:
arr = [
{
"key": None,
"anotherkey": 0
},
{
"another": "ignore"
},
{
"bool": True,
"key": "this!"
}
]
有一条班轮可以做这件事吗?我用for循环做的。
您可以循环内部字典,并使用next
:中的生成器表达式检查不是None
的key
>>> next((d['key'] for d in arr if d.get('key') is not None), None)
'this!'
这将返回与'key'
相关联的第一个值,否则,如果不存在这样的键/值对,则返回None
。