1

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)
Elias Zamaria
  • 96,623
  • 33
  • 114
  • 148
user3817250
  • 1,003
  • 4
  • 14
  • 27

2 Answers2

5

You could call the function using the double-star for kwargs:

def call_foo(arg_dict):
    foo(**arg_dict)

This means you probably don't even need call_foo to begin with.

This StackOverflow post has a good amount of detail if you want to know more about how the star and double-star arguments work.

Community
  • 1
  • 1
robbrit
  • 17,560
  • 4
  • 48
  • 68
1

You can simply call

def call_foo(arg_dict):
    foo(**arg_dict)

You created a arg_list (no need of it). But if any chance, you can pass list as arguments,

def call_foo(arg_dict):
    foo(*arg_list)  

It takes arguments to corresponding index of list.

Also no need of if 'a' in dict and 'b' in dict and 'c' in dict:, Just

args = ['a','b','c']
if all([(i in arg_dict) for i in args]):

Dont use dict as variable name or arguments, it may override builtin dict

Corey
  • 1,532
  • 9
  • 12
itzMEonTV
  • 19,851
  • 4
  • 39
  • 49