[英]First non-null value from a list of dicts
Let's suppose that I want to get the first value of key
that is not null inside this list of dicts:假设我想在这个字典列表中获取不是null 的
key
的第一个值:
arr = [
{
"key": None,
"anotherkey": 0
},
{
"another": "ignore"
},
{
"bool": True,
"key": "this!"
}
]
Is there some one-liner to do this?是否有一些单线可以做到这一点? I made it using a for loop.
我使用 for 循环实现了它。
You can loop over the inner dictionaries and check for a key
that isn't None
using a generator expression within next
:您可以遍历内部字典并使用
next
中的生成器表达式检查不是None
的key
:
>>> next((d['key'] for d in arr if d.get('key') is not None), None)
'this!'
This will return the first value associated with 'key'
, otherwise None
if no such key/value pairs exist.这将返回与
'key'
关联的第一个值,否则返回None
如果不存在这样的键/值对。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.