Dhanushka Amarakoon
Dhanushka Amarakoon

Reputation: 3762

Python building multiple arg parameters

I want to convert certain values of a dictionary as multiple args and pass it to a method. The key of the dict needs to be the name of the variable passed to the method.

eg:

myDict={'one':1,'two':2,'three':3,'four':4}

#call myMethod as
myMethod(one=1,two=2)

def myMeth(self,*args):
     do somthing with args

Upvotes: 1

Views: 62

Answers (2)

Valkyrie
Valkyrie

Reputation: 861

Use ** for passing or accepting dictionary arguments. The following code

d={'foo': 'bar','test': 123}

def my_method(**kwargs):
    print kwargs

my_method(**d)

would print the contents of d, {'foo': 'bar','test': 123}

EDIT: @Matthew 's answer sums it up nicely, via the comparison of *args.

Upvotes: 0

Matthew
Matthew

Reputation: 7590

You can use the unpacking notation. If you have a method like this

def function(arg1,arg2,arg3):
    # do something

and a dictionary dct = {'arg1':3,'arg2':3,'arg3':6}, you can call the function like

function(**dct)

which is equivalent to doing function(arg1=3,arg2=3,arg3=6).

Notice the double stars. This means to take the dictionary and pass its values as named parameters where the keys are the names. A single star would unpack a list, passing its values in order as unnamed parameters. These can be combined.

See section 4.7.4 of the python documentation for more detail. Here is another article discussing these as well.

Upvotes: 1

Related Questions