John
John

Reputation: 2952

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

We often have functions like this:

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)

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 {})
)

Upvotes: 0

Views: 70

Answers (2)

pho
pho

Reputation: 25490

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}

    ...

Upvotes: 1

Joran Beasley
Joran Beasley

Reputation: 114038

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 ...

Upvotes: 1

Related Questions