You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用一行代码从字典列表中取出指定key对应的首个非null值?

问题场景

我们需要从如下字典列表中,提取key对应的第一个不为null的值:

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

现有方案是用for循环实现,求一行实现方式。

一行实现方案

直接用next()搭配生成器表达式即可实现,执行效率和手动for循环完全一致,都是找到第一个匹配项就停止遍历:

res = next(d['key'] for d in arr if 'key' in d and d['key'] is not None)

运行上述代码得到的结果就是this!,符合预期。

如果要处理没有匹配项的情况(避免抛出StopIteration异常),可以给next()加第二个默认返回参数:

# 找不到匹配项时默认返回None
res = next((d['key'] for d in arr if 'key' in d and d['key'] is not None), None)

内容的提问来源于stack exchange,提问作者Rodrigo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 04:54:02