user469652
user469652

Reputation: 51241

Python: pass more than one keyword argument?

is there possible to pass more than one keyword argument to a function in python?

foo(self, **kwarg)      # Want to pass one more keyword argument here

Upvotes: 0

Views: 2115

Answers (4)

John La Rooy
John La Rooy

Reputation: 304167

Maybe this helps. Can you clarify how the kw arguments are divided into the two dicts?

>>> def f(kw1, kw2):
...  print kw1
...  print kw2
... 
>>> f(dict(a=1,b=2), dict(c=3,d=4))
{'a': 1, 'b': 2}
{'c': 3, 'd': 4}

Upvotes: 1

aaronasterling
aaronasterling

Reputation: 71004

I would write a function to do this for you

 def partition_mapping(mapping, keys):
     """ Return two dicts. The first one has key, value pair for any key from the keys
         argument that is in mapping and the second one has the other keys from              
         mapping
     """
     # This could be modified to take two sequences of keys and map them into two dicts
     # optionally returning a third dict for the leftovers
     d1 = {}
     d2 = {}
     keys = set(keys)
     for key, value in mapping.iteritems():
         if key in keys:
             d1[key] = value
         else:
             d2[key] = value
     return d1, d2

You can then use it like this

def func(**kwargs):
    kwargs1, kwargs2 = partition_mapping(kwargs, ("arg1", "arg2", "arg3"))

This will get them into two separate dicts. It doesn't make any sense for python to provide this behavior as you have to manually specify which dict you want them to end up in. Another alternative is to just manually specify it in the function definition

def func(arg1=None, arg2=None, arg3=None, **kwargs):
    # do stuff

Now you have one dict for the ones you don't specify and regular local variables for the ones you do want to name.

Upvotes: 2

Senthil Kumaran
Senthil Kumaran

Reputation: 56841

You cannot. But keyword arguments are dictionaries and when calling you can call as many keyword arguments as you like. They all will be captured in the single **kwarg. Can you explain a scenario where you would need more than one of those **kwarg in the function definition?

>>> def fun(a, **b):
...     print b.keys()
...     # b is dict here. You can do whatever you want.
...     
...     
>>> fun(10,key1=1,key2=2,key3=3)
['key3', 'key2', 'key1']

Upvotes: 1

C. K. Young
C. K. Young

Reputation: 223013

You only need one keyword-arguments parameter; it receives any number of keyword arguments.

def foo(**kwargs):
  return kwargs

>>> foo(bar=1, baz=2)
{'baz': 2, 'bar': 1}

Upvotes: 5

Related Questions