0

I require a simple method to pass only required arguments to a function which takes in multiple arguments.

def sample1(arg1=0,arg2=0,arg3=0 ... ...  argn=0)

Argument Dictionary

argument_dictionary={'arg1':0,'arg4':1}

I want to iterate through the argument_dictionary and pass only arg1 and arg4 to sample1 as

sample1(arg1=0,arg4=1)
user2864740
  • 60,010
  • 15
  • 145
  • 220
shivram
  • 469
  • 2
  • 10
  • 26
  • related information: http://stackoverflow.com/questions/919680/can-a-variable-number-of-arguments-be-passed-to-a-function?rq=1 – user2864740 Dec 07 '15 at 04:20

3 Answers3

7

This is done with keyword argument unpacking in which "dictionaries can deliver keyword arguments":

sample1(**argument_dictionary)

Demo:

>>> def sample1(arg0=0, arg1=0, arg2=0, arg3=0, arg4=0):
...   print(locals())
... 
>>> argument_dictionary = {'arg0': 1, 'arg4': 4}
>>> sample1(**argument_dictionary)
{'arg0': 1, 'arg1': 0, 'arg2': 0, 'arg3': 0, 'arg4': 4}
mgilson
  • 300,191
  • 65
  • 633
  • 696
2

I am a little uncertain if this is exactly what you meant, but you can do **argument_dictionary in the function call to suit your needs. It will expand out the k, v pairs for you.

jheld
  • 148
  • 2
  • 8
0

Just pass an argument hash. In your subfunction, iterate through the hash.

def sample1(argument_dictionary) :
  for(key, value) in argument_dictionary.items():
    ...

Example calls:

sample({'arg1': 0, 'arg4': 1})
sample({'arg1': 0})

argument_dictionary = {'arg1': 0, 'arg4': 1}
sample(argument_dictionary)
noctrnal
  • 191
  • 4
  • You make the assumption that the user can change the implementation of the function, instead of helping them learn a new bit of python syntax which would probably be more overall useful. End of rant. – jheld Dec 07 '15 at 04:24
  • OP stated "I want to iterate through the argument_dictionary"... which might lead one to that assumption. Syntax still learned on iterating and foreach and introduced to the idea of a params hash instead of list of parameters. – noctrnal Dec 07 '15 at 04:31
  • You could go that route. However, python does not have a built in foreach. You are different, not wrong. In this case of different, not as right. Had the OP wanted your answer, you would have an up or solve for it. Merely stating context here. – jheld Dec 07 '15 at 11:33