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

Python中如何从可能为None的字典中取值(单行代码实现)

解决方案

可以用以下几种单行代码实现需求:

  • 三元表达式写法:

    result = my_dic.get('name') if my_dic is not None else None
    

    逻辑直接明了:先判断my_dic是否不为None,满足条件则调用get()方法取值,否则返回None。

  • 短路求值写法:

    result = my_dic and my_dic.get('name')
    

    利用Python逻辑与的短路特性:如果my_dic是None,表达式直接返回None;如果my_dic有效,则执行后半部分的get()方法并返回结果。注:如果my_dic是其他假值(比如空字典{}),这种写法会返回空字典而非None,仅适合只需要处理my_dic为None的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.16 03:07:02