将字典发送到不接受 **kwargs 的函数?
我最近才开始了解 **kwargs 的奇迹,但我遇到了绊脚石。有没有办法将字典的关键字发送到不接受关键字参数的函数? 考虑以下简单的设置:
def two(**kwargs):
return kwargs['second']
def three(**kwargs):
return kwargs['third']
parameterDict = {}
parameterDict['first'] = 1
parameterDict['second'] = 2
parameterDict['third'] = 3
我使用一些以以下样式进行接口的外部代码:
fitObject = externalCode(two, first=1, second=2)
问题是:“externalCode”不接受 **kwargs,那么有没有一种聪明的方法可以将字典信息转换为可接受的形式?
此外,不同的函数采用parameterDict的不同子集作为参数。因此,函数“two”可能接受“第一个”和“第二个”参数,但拒绝“第三个”。而“三”则接受这三者。
- - - - - - - - - - - - - - - - - - - 编辑 - - - - - - -------------------------
人们正确地评论说上面的代码不会失败 - 所以我已经找到了我的问题,并且我不确定是否值得重新发布。我正在做这样的事情:
def printHair(**kwargs):
if hairColor == 'Black':
print 'Yep!'
pass
personA = {'hairColor':'blue'}
printHair(**personA)
NameError: global name 'hairColor' is not defined
而且,显然解决方法是在定义时显式包含 hairColor: printHair(hairColor, **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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以使用关键字扩展运算符 (
**
) 将字典解包为函数参数。You can use the keyword expansion operator (
**
) to unpack a dictionary into function arguments.使用 get 怎么样
How about using get