I want to pass the element of the same dictionary to several functions with kwargs. The problem is that this dictionary contains more than the functions receive in their arguments list.
For example, lets say I have the following dictionary:
d = dict(a=1,b=2,c=3)
Now, I'll use it in a function that receives the parameters in the dict - and it will work:
def func1(a=3,b=2,c=5):
return a b c
x = func1(**d)
BUT, if the function receives fewer parameters than the dict, it will rightfully result in an error:
def func2(a=1,b=1):
return a b
x = func2(**d)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
Cell In [4], line 4
1 def func2(a=1,b=1):
2 return a b
----> 4 x = func2(**d)
TypeError: func2() got an unexpected keyword argument 'c'```
Is there a way to make this scenario work, without having to re-arrange my functions arguments? Maybe by creating a subset of the dict? Is there a short and elegant way to fit a dict to a function?
CodePudding user response:
You can us *args
and **kwargs
for that.
Just define your function with
def func(a, b, **kwargs):
return a b
and it should work. Might be a quick and dirty solution, though... :-)