开发者

Is there a shorthand in Python for adding optional keys to a dict?

开发者 https://www.devze.com 2022-12-07 22:45 出处:网络
We often have functions like this: def my_func(arg1, arg2, arg3=None, arg4=None): params = dict(arg1=arg1,开发者_如何学C arg2=arg2)

We often have functions like this:

def my_func(arg1, arg2, arg3=None, arg4=None):
    params = dict(arg1=arg1,开发者_如何学C arg2=arg2)

    if arg3:
        params["arg3"] = arg3

    if arg4:
        params["arg4"] = arg4

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

The endpoint being hit will NOT be happy with a key in params set to a value of None. It expects that if arg3 or arg4 isn't required, it won't be present in params at all.

Is there a shorthand for constructing the params dict that doesn't require one if-statement per optional param? Something less ugly than:

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


def my_func(arg1, arg2, **kwargs):
    optional_kwargs = ['arg3','arg4']
    params = dict(arg1=arg1, arg2=arg2)
    params.update({k:v for k,v in kwargs.items() if k in optional_kwargs})
    response = requests.post("https://...", data=params)

Is what i would do ...


You could add everything to the dict and then filter out the None values:

def my_func(arg1, arg2, arg3=None, arg4=None):
    params = {k: v for k, v in dict(arg1=arg1, arg2=arg2, arg3=arg3, arg4=arg4).items() if v is not None}

    ...
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号