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

Question:

I have a function that accepts wildcard keyword parameters:

def func(**kargs):
    doA
    doB

How do I send it a dictionary?

Asked By: flybywire

||

Answers:

func(**mydict)

this will mean kwargs=mydict inside the function

all the keys of mydict must be strings

Answered By: John La Rooy

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.

Answered By: nosklo

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.

Answered By: edvald

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)
Answered By: SamuelN

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)
Answered By: Willie Cheng
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.