Skip to content
Advertisement

Pass a dictionary as default arguments of a function

let’s say i have a function like this:

def foo (a = "a", b="b", c="c", **kwargs):
    #do some work

I want to pass a dict like this to the function as the only argument.

arg_dict = {
    "a": "some string"
    "c": "some other string"
}

which should change the values of the a and c arguments but b still remains the default value.

since foo is in an external library i don’t want to change the function itself.

is there any way to achieve this?

EDIT

to clarify foo has both default arguments like a and has keyword arguments like **kwargs

when i do this:

foo(**arg_dict)

**arg_dict is passed as the **kwargs and other arguments stay the default value.

Advertisement

Answer

You can unpack the arg_dict using ** operator.

>>> def foo (a = "a", b="b", c="c", **kwargs):
...     print(f"{a=}")
...     print(f"{b=}")
...     print(f"{c=}")
...     print(f"{kwargs=}")
... 
>>> arg_dict = {
...     "a": "some string",
...     "c": "some other string",
...     "addional_kwrag1": 1
... }
>>> 
>>> foo(**arg_dict)
a='some string'
b='b'
c='some other string'
kwargs={'addional_kwrag1': 1}
Advertisement