Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a Dict to a function with Keyword arguments?

Let's assume I have this Dict:

d=Dict("arg1"=>10,"arg2"=>20)

and a function like this:

function foo(;arg1,arg2,arg3,arg4,arg5)
  #Do something
end

How can I call the function and pass the parameters in the Dict d as parameters for the function? I know I can do this:

foo(arg1=d["arg1"],arg2=d["arg2"])

But is there any way to automate this? I mean a way to figure out which arguments are defined in the Dict and pass it automatically to the function.

like image 507
ahm5 Avatar asked Oct 19 '21 11:10

ahm5


People also ask

How do you pass a dictionary item as a function argument in Python?

Passing Dictionary as kwargs “ kwargs ” stands for keyword arguments. It is used for passing advanced data objects like dictionaries to a function because in such functions one doesn't have a clue about the number of arguments, hence data passed is be dealt properly by adding “**” to the passing type.

How do you pass a dict as Kwargs?

Precede double stars ( ** ) to a dictionary argument to pass it to **kwargs parameter. Always place the **kwargs parameter at the end of the parameter list, or you'll get an error.

Is dict () and {} the same?

tl;dr. With CPython 2.7, using dict() to create dictionaries takes up to 6 times longer and involves more memory allocation operations than the literal syntax. Use {} to create dictionaries, especially if you are pre-populating them, unless the literal syntax does not work for your case.

How do you use keyword arguments in Python?

Embrace keyword arguments in Python Consider using the * operator to require those arguments be specified as keyword arguments. And remember that you can accept arbitrary keyword arguments to the functions you define and pass arbitrary keyword arguments to the functions you call by using the ** operator.


1 Answers

Dictionaries with Symbol keys can be directly splatted into the function call:

julia> d = Dict(:arg1 => 10, :arg2 => 12)
Dict{Symbol, Int64} with 2 entries:
  :arg1 => 10
  :arg2 => 12

julia> f(; arg1, arg2) = arg1 + arg2
f (generic function with 1 method)

julia> f(; d...)
22

Note the semicolon in the function call, which ensure that the elements in d are interpreted as keyword arguments instead of positional arguments which just happen to be Pairs.

like image 55
pfitzseb Avatar answered Oct 15 '22 02:10

pfitzseb