[ACCEPTED]-How to send a dictionary to a function that accepts **kwargs?-python

Accepted answer
Score: 64

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

This is documented 2 on section 4.7.4 of python tutorial.

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

Score: 8

It's not 100% clear by your question, but 10 if you'd like to pass a dict in through kwargs, you 9 just make that dict a part of another dict, like 8 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')


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

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

Score: 5


this will mean kwargs=mydict inside the 1 function

all the keys of mydict must be strings

Score: 2

for python 3.6 just put ** before the dictionary 1 name

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

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

Score: 0

Easy way to pass parameters with a variable, args, and 1 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):
    return z


a = random_func(z,*y,**x)

More Related questions