Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send dictionary to function that does not accept **kwargs?

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.

like image 913
JBWhitmore Avatar asked Sep 05 '25 23:09

JBWhitmore


2 Answers

>>> def externalCode(two, first=1, second=2):
...     print two, first, second
... 
>>> params = {'two': 9, 'first': 8, 'second': 7}
>>> externalCode(**params)
9 8 7
like image 86
jonesy Avatar answered Sep 08 '25 21:09

jonesy


You can use the keyword expansion operator (**) to unpack a dictionary into function arguments.

fitObject = externalCode(two, **parameterDict)
like image 24
Ignacio Vazquez-Abrams Avatar answered Sep 08 '25 22:09

Ignacio Vazquez-Abrams