Suppose I have some function, f
:
JavaScript
x
3
1
def f (a=None):
2
print a
3
Now, if I have a dictionary such as dct = {"a":"Foo"}
, I may call f(**dct)
and get the result Foo
printed.
However, suppose I have a dictionary dct2 = {"a":"Foo", "b":"Bar"}
. If I call f(**dct2)
I get a
JavaScript
1
2
1
TypeError: f() got an unexpected keyword argument 'b'
2
Fair enough. However, is there anyway to, in the definition of f
or in the calling of it, tell Python to just ignore any keys that are not parameter names? Preferable a method that allows defaults to be specified.
Advertisement
Answer
As an extension to the answer posted by @Bas, I would suggest to add the kwargs arguments (variable length keyword arguments) as the second parameter to the function
JavaScript
1
8
1
>>> def f (a=None, **kwargs):
2
print a
3
4
5
>>> dct2 = {"a":"Foo", "b":"Bar"}
6
>>> f(**dct2)
7
Foo
8
This would necessarily suffice the case of
- to just ignore any keys that are not parameter names
- However, it lacks the default values of parameters, which is a nice feature that it would be nice to keep