0

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 
2
  • as Chris says below, your function would accept any number of keyword arguments without any changes. Commented Jan 11, 2011 at 2:37
  • What are you trying to do that needs this? Commented Jan 11, 2011 at 3:05

4 Answers 4

5

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} 
Sign up to request clarification or add additional context in comments.

3 Comments

I just want them in two separate dictionary.
@user469652, that's a very strange request.
@user469652: How would you decide which dictionary should hold which keys?
2

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.

Comments

1

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'] 

2 Comments

I somehow has to make some values go into another dictionary. Otherwise, it won't work.
The arg you pass, 'b' is actually a dict. You can do any dict operation there. Copy the keys and values conditionally, etc.
1

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} 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.