[英]First non-null value from a list of dicts
假設我想在這個字典列表中獲取不是null 的key
的第一個值:
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
如果不存在這樣的鍵/值對。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.