Reputation: 12316
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.
Upvotes: 4
Views: 1267
Reputation: 1
How about using get
def printHair(**kwargs):
#check if hair colour is in kwargs
#if it is not you can set a default, otherwise default is None
personA['hairColor'] = kwargs.get('hairColor','Blue')
printHair(**personA)
Upvotes: 0
Reputation: 3542
>>> def externalCode(two, first=1, second=2):
... print two, first, second
...
>>> params = {'two': 9, 'first': 8, 'second': 7}
>>> externalCode(**params)
9 8 7
Upvotes: 3
Reputation: 799520
You can use the keyword expansion operator (**
) to unpack a dictionary into function arguments.
fitObject = externalCode(two, **parameterDict)
Upvotes: 1