I just recently have started learning about the wonders of **kwargs but I've hit a stumbling block. Is there a way of sending keywords of a dictionary to a function that does not accept keyword arguments? Consider the following simple setup:
def two(**kwargs):
return kwargs['second']
def three(**kwargs):
return kwargs['third']
parameterDict = {}
parameterDict['first'] = 1
parameterDict['second'] = 2
parameterDict['third'] = 3
I use some external code that interfaces in the following style:
fitObject = externalCode(two, first=1, second=2)
The problem is: "externalCode" does not accept **kwargs, so is there a smart way of getting the dictionary information into an acceptable form?
Also, the different functions take as parameters different subsets of the parameterDict. So, the function "two" might accept the "first" and "second" parameters, it rejects the "third". And "three" accepts all three.
------------------------------------- EDIT -------------------------------------
People have correctly commented that the above code won't fail -- so I've figured out my problem, and I'm not sure if it's worth a repost or not. I was doing something like this:
def printHair(**kwargs):
if hairColor == 'Black':
print 'Yep!'
pass
personA = {'hairColor':'blue'}
printHair(**personA)
NameError: global name 'hairColor' is not defined
And, apparently the fix is to explicitly include hairColor when defining: printHair(hairColor, **kwargs) in the first place.
>>> def externalCode(two, first=1, second=2):
... print two, first, second
...
>>> params = {'two': 9, 'first': 8, 'second': 7}
>>> externalCode(**params)
9 8 7
You can use the keyword expansion operator (**
) to unpack a dictionary into function arguments.
fitObject = externalCode(two, **parameterDict)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With