[英]How to send a dictionary to a function that accepts **kwargs?
我有一个接受通配符关键字参数的函数:
def func(**kargs):
doA
doB
如何发送字典?
只需使用func(**some_dict)
进行调用即可。
请注意, 同一 dict
未传递到函数中。 创建了一个新副本,因此some_dict is not kwargs
。
这不是100%由你的问题不清楚,但如果你想传递一个dict
通过kwargs
,你只是使字典另一个字典的一部分,就像这样:
my_dict = {} #the dict you want to pass to func
kwargs = {'my_dict': my_dict } #the keyword argument container
func(**kwargs) #calling the function
然后,您可以在函数中捕获my_dict
:
def func(**kwargs):
my_dict = kwargs.get('my_dict')
要么...
def func(my_dict, **kwargs):
#reference my_dict directly from here
my_dict['new_key'] = 1234
当我将一组相同的选项传递给不同的函数时,我会大量使用后者,但是某些函数仅使用某些选项(我希望这是有道理的...)。 但是,当然有一百万种方法可以做到这一点。 如果您对您的问题有所阐述,我们很可能会为您提供更好的帮助。
func(**mydict)
这意味着函数内部为kwargs = mydict
mydict的所有键必须是字符串
对于python 3.6只需在字典名称前加上**
def lol(**kwargs):
for i in kwargs:
print(i)
my_dict = {
"s": 1,
"a": 2,
"l": 3
}
lol(**my_dict)
通过Decorator传递带有变量,args和kwargs的简单方法
def printall(func):
def inner(z,*args, **kwargs):
print ('Arguments for args: {}'.format(args))
print ('Arguments for kwargs: {}'.format(kwargs))
return func(*args, **kwargs)
return inner
@printall #<-- you can mark Decorator,it will become to send some variable data to function
def random_func(z,*y,**x):
print(y)
print(x)
return z
z=1
y=(1,2,3)
x={'a':2,'b':2,'c':2}
a = random_func(z,*y,**x)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.