[ACCEPTED]-How to send a dictionary to a function that accepts **kwargs?-python
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
.
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')
or...
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.
func(**mydict)
this will mean kwargs=mydict inside the 1 function
all the keys of mydict must be strings
for python 3.6 just put ** before the dictionary 1 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 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):
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)
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.