开发者

How to send a dictionary to a function that accepts **kwargs?

I have a function that accepts wildcard keyword p开发者_Python百科arameters:

def func(**kargs):
    doA
    doB

How do I send it a dictionary?


Just use func(**some_dict) to call it.

This is documented on section 4.7.4 of python tutorial.

Note that the same dict is not passed into the function. A new copy is created, so some_dict is not kwargs.


It's not 100% clear by your question, but if you'd like to pass a dict in through kwargs, you just make that dict a part of another dict, like so:

my_dict = {}                       #the dict you want to pass to func
kwargs  = {'my_dict': my_dict }    #the keyword argument container
func(**kwargs)                     #calling the function

Then you can catch my_dict in the function:

def func(**kwargs):
    my_dict = kwargs.get('my_dict')

or...

def func(my_dict, **kwargs):
    #reference my_dict directly from here
    my_dict['new_key'] = 1234

I use the latter a lot when I have the same set of options passed to different functions, but some functions only use some the options (I hope that makes sense...). But there are of course a million ways to go about this. If you elaborate a bit on your problem we could most likely help you better.


func(**mydict)

this will mean kwargs=mydict inside the function

all the keys of mydict must be strings


for python 3.6 just put ** before the dictionary name

def lol(**kwargs):
    for i in kwargs:
        print(i)

my_dict = {
    "s": 1,
    "a": 2,
    "l": 3
}

lol(**my_dict)


Easy way to pass parameters with a variable, args, and kwargs with Decorator

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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜