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

Python中构建不含None值可选键的字典是否有简写方法?

问题:简洁构建不含None值键的请求参数字典

我们经常写这样的函数:

def my_func(arg1, arg2, arg3=None, arg4=None):
    params = dict(arg1=arg1, arg2=arg2)

    if arg3:
        params["arg3"] = arg3

    if arg4:
        params["arg4"] = arg4

    response = requests.post("https://...", data=params)

由于请求接口不接受字典中存在值为None的键,要求可选参数(比如arg3、arg4)未传值时,对应的键完全不出现于params中。

有没有更简洁的方式构建这个params字典?不需要给每个可选参数写一条if语句,比如比以下写法更简洁的实现:

params = (
    dict(arg1=arg1, arg2=arg2)
    | (dict(arg3=arg3) if arg3 else {})
    | (dict(arg4=arg4) if arg4 else {})
)

几种简洁实现方式

1. 字典推导式(手动指定参数,最稳妥)

把所有参数的键值对列出来,通过推导式过滤掉值为None的项:

def my_func(arg1, arg2, arg3=None, arg4=None):
    params = {
        key: value
        for key, value in [
            ("arg1", arg1),
            ("arg2", arg2),
            ("arg3", arg3),
            ("arg4", arg4)
        ]
        if value is not None
    }
    response = requests.post("https://...", data=params)

这种方式完全可控,不会引入函数内的其他局部变量,适合参数数量不多的场景。

2. 结合filter函数

用filter过滤掉值为None的键值对,再转成字典:

def my_func(arg1, arg2, arg3=None, arg4=None):
    params = dict(
        filter(
            lambda item: item[1] is not None,
            [("arg1", arg1), ("arg2", arg2), ("arg3", arg3), ("arg4", arg4)]
        )
    )
    response = requests.post("https://...", data=params)

逻辑和字典推导式类似,写法上更偏向函数式风格。

3. 基础字典+可选参数过滤合并(Python 3.9+)

把必填参数和可选参数分开,过滤可选参数后再合并到基础字典:

def my_func(arg1, arg2, arg3=None, arg4=None):
    base_params = {"arg1": arg1, "arg2": arg2}
    optional_params = {"arg3": arg3, "arg4": arg4}
    params = base_params | {k: v for k, v in optional_params.items() if v is not None}
    response = requests.post("https://...", data=params)

结构清晰,必填和可选参数划分明确,适合参数较多的场景。

4. 利用locals()简化(慎用)

如果函数内没有其他额外局部变量,可以直接用locals()获取所有参数,再过滤:

def my_func(arg1, arg2, arg3=None, arg4=None):
    params = {k: v for k, v in locals().items() if v is not None}
    response = requests.post("https://...", data=params)

这种写法最简洁,但如果函数内定义了其他变量(比如临时变量),会被误加入params,所以只适合函数逻辑简单的情况。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 03:31:05