簡體   English   中英

字典列表中的第一個非空值

[英]First non-null value from a list of dicts

假設我想在這個字典列表中獲取不是null 的key的第一個

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如果不存在這樣的鍵/值對。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM