I'm attempting to do a function call with the values of a dictionary.
The function takes a number of arguments, most with default values.
def foo(name, a=None, b='', c=12):
print(name,a,b,12)
If the dictionary is fully populated the function call would look like this.
def call_foo(arg_dict):
foo(name=arg_dict['name'], a=arg_dict['a'], b=arg_dict['b'], c=arg_dict['c'])
I need to make the function call dependent on whether or not those keys actually exist in the dictionary though. So that if only a subset of the arguments exist, I'm only passing those arguments.
def call_foo(arg_dict):
if 'a' in arg_dict and 'b' in arg_dict and 'c' in arg_dict:
foo(name=arg_dict['name'], a=arg_dict['a'], b=arg_dict['b'], c=arg_dict['c'])
elif 'a' in arg_dict and 'c' in arg_dict:
foo(name=arg_dict['name'], a=arg_dict['a'], c=arg_dict['c'])
This type of expression will quickly become unmanageable with a larger number of optional arguments.
How can I define a named argument list to pass to foo? Something similar to the following.
def call_foo(arg_dict):
arg_list = []
arg_list.append(name=arg_dict['name'])
if 'a' in arg_dict:
arg_list.append(a=arg_dict['a'])
if 'b' in arg_dict:
arg_list.append(b=arg_dict['b'])
if 'c' in arg_dict:
arg_list.append(c=arg_dict['c'])
foo(arg_list)